1053 Path of Equal Weight

题目:

 题意:

  给定一棵树和每个结点的权值,求所有从根结点到叶子结点的路径,使得每条路径上的结点的权值之和等于给定的常数S。如果存在多条路径,则按路径非递增顺序输出。

输入样例:

20 9 24
10 2 4 3 5 10 2 18 9 7 2 2 1 3 12 1 8 6 2 2
00 4 01 02 03 04
02 1 05
04 2 06 07
03 3 11 12 13
06 1 09
07 2 08 10
16 1 15
13 3 14 16 17
17 2 18 19

输出样例:

10 5 2 7
10 4 10
10 3 3 6 2
10 3 3 6 2

 第一次使用静态数组存放一棵树,即数组下标表示结点的编号,数组的内容表示权值和孩子结点(下标)的集合

 1 #include<iostream>
 2 #include<vector>
 3 #include<algorithm>
 4 using namespace std;
 5 const int maxn = 200;
 6 
 7 struct Node {
 8     int weight;//数据域 ,即权值 
 9     vector<int> child;//指针域,即孩子结点的下标集合 
10 } node[maxn]; //结点数组 
11 
12 int n,m,s;//结点个数、非叶结点个数、要求的叶子结点的带权路径和
13 vector<int> path;
14 
15 bool cmp(const int& a,const int& b) { //按结点的数据域 递减排序
16     return node[a].weight > node[b].weight;
17 }
18 void DFS(int index,int weightSum) { //index表示 结点在node中的编号
19     if(weightSum > s) return ;
20     else if(weightSum == s) {
21         if(node[index].child.size() == 0) { // 是叶子结点
22             for(int i = 0; i < path.size(); ++i) {
23                 if(i > 0) printf(" ");
24                 cout<<node[path[i]].weight;
25             }
26             cout<<endl;
27         }
28         return ;
29     }
30     for(int i = 0; i < node[index].child.size(); ++i) {//枚举所有孩子结点 
31         int child = node[index].child[i];
32         path.push_back(child);  
33         DFS(child,weightSum + node[child].weight);
34         path.pop_back();
35     }
36 }
37 
38 int main() {
39     cin>>n>>m>>s;
40     for(int i = 0; i < n; ++i)//初始化每个结点的权值
41         cin>>node[i].weight;
42     int id,k,child;
43     for(int i = 0; i < m; ++i) {//初始化非叶结点的孩子,构造一棵树
44         cin>>id>>k;
45         for(int j = 0; j < k; ++j) {
46             cin>>child;
47             node[id].child.push_back(child);
48         }
49         sort(node[id].child.begin(),node[id].child.end(),cmp);
50     }
51     path.push_back(0);// 不要忘了保存路径的第一个结点
52     DFS(0,node[0].weight); //从根结点0开始
53     return 0;
54 }

 

posted @ 2020-03-01 12:23  tangq123  阅读(160)  评论(0编辑  收藏  举报