现有一棵n个结点的树(结点编号为从0到n-1,根结点为0号结点),每个结点有各自的权值w。
求这棵树的带权路径长度。

解题思路:每个节点存储weight和height值。
然后利用遍历,当遍历到叶子节点时候,sumweight加上当前节点的带权路径值。
完整代码如下:
- #include
- #include
- using namespace std;
-
- struct node{
- int height = 0;
- int weight;
- vector<int> child;
- } nodes[51];
- bool flag = false;
- int sumweight = 0;
-
- void PreOrderTraverse(int root){
- if(root == -1){
- return ;
- }
- if(nodes[root].child.size()==0){
- sumweight += nodes[root].weight*nodes[root].height;
- }
- for(int i=0;i
size();i++){ - nodes[nodes[root].child[i]].height = nodes[root].height+1;
- PreOrderTraverse(nodes[root].child[i]);
- }
- }
-
- int main(){
- int n;
- cin>>n;
- for(int i=0;i
- cin>>nodes[i].weight;
- }
- for(int i=0;i
- int k;
- cin>>k;
- int temp;
- for(int j=0;j
- cin>>temp;
- nodes[i].child.push_back(temp);
- }
- }
- PreOrderTraverse(0);
- cout<
- return 0;
- }
-
相关阅读:
ctrl+k,ctrl+l无法切换到时限文件
使用ffmpeg把MP4不能在浏览器中播放转换,转换速度10秒内超快
【推荐系统】什么是好的推荐系统?个性化和非个性化推荐
【C++设计模式之模板模式】分析及示例
通过自学可以搭建量化交易模型吗?
JavaScript 33 JavaScript 数学
小程序源码:纯头像微信小程序源码下载,多分类头像自动采集无需服务器和域名-多玩法安装简单
若依框架解读(前后端分离版)—— 1.Spring Security相关配置(@Anonymous注解)
JVM 第四部分—垃圾回收概念 和 算法 1
XPath从入门到精通:基础和高级用法完整指南,附美团APP匹配示例
-
原文地址:https://blog.csdn.net/u011708235/article/details/134492325