1053 Path of Equal Weight
大致题意就是给出一棵树,求出叶子结点的带权路径长度等于 S的路径(即根结点到叶子结点的路径上的点权权值之和),如果有多条路径序列,那么按反字典序输出它们。
1 #include<iostream> 2 #include<vector> 3 #include<algorithm> 4 using namespace std; 5 const int maxn = 200; 6 struct Node { 7 int weight; 8 vector<int> child; 9 } node[maxn]; 10 11 vector<int> v; 12 int n,m,s; 13 bool cmp(const int& a, const int& b) { //把孩子结点按权值递减排序 14 return node[a].weight > node[b].weight; 15 } 16 void DFS(int root,int nowSum) { //树的先序遍历 17 if(node[root].child.size() == 0) { //叶子节点 18 if(nowSum == s) { //叶子结点的带权路径之和 等于 S 19 for(int i = 0; i < v.size(); ++i) { 20 if(i > 0) printf(" "); 21 printf("%d",node[v[i]].weight); 22 } 23 printf("\n"); 24 } 25 return ; 26 } 27 for(int i = 0; i < node[root].child.size(); ++i) { 28 int child = node[root].child[i]; 29 v.push_back(child); //孩子结点入栈 30 DFS(child,nowSum + node[child].weight); 31 v.pop_back();//出栈 32 } 33 } 34 35 int main() { 36 cin>>n>>m>>s; 37 for(int i = 0; i < n; ++i) //初始化每个结点的权值 38 cin>>node[i].weight; 39 for(int i = 0; i < m; ++i) { //构造一棵树 40 int parent,k,child; 41 cin>>parent>>k; 42 for(int j = 0; j < k; ++j) { 43 cin>>child; 44 node[parent].child.push_back(child); 45 } 46 sort(node[parent].child.begin(),node[parent].child.end(),cmp);//把孩子结点按权值递减排序,方便后序按字典递减序输出路径 47 } 48 v.push_back(0); //根结点入栈 49 DFS(0,node[0].weight); 50 return 0; 51 }