现有一棵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;
- }
-
相关阅读:
【已解决】扫描mapper包
短视频如何展现效果更佳?不用类型的短视频有不同的侧重点
百度地图自定义覆盖物(html)格式
计算机视觉中的可解释性分析
uniapp 中app通过视频链接获取封面
TCP的三次握手和四次挥手 | 查看网络状态
Python xpath 入门使用
蓝桥杯DP算法——背包问题(C++)
c++旅行商问题 (暴力解)
我的企业证书是正常的但是下载应用app到手机提示无法安装“app名字”无法安装此app,因为无法验证其完整性解决方案
-
原文地址:https://blog.csdn.net/u011708235/article/details/134492325