1053 Path of Equal Weight (30 分)(树的遍历)
给定一棵树和每个结点的权值,求所有从根结点到叶子结点的路径,让每条路径上的结点的权值之和等于给定的常数,如果有多条这样的路径,按照非递增的顺序输出
#include<iostream> #include<vector> #include<algorithm> using namespace std; int n, m, s; const int maxn = 110; struct node { int weight; vector<int>child; }Node[maxn]; vector<int>ans; bool comp(int a, int b) { return Node[a].weight > Node[b].weight; } void DFS(int index, int sum) { if (sum == s) { if (Node[index].child.size() != 0)return; for (int i = 0; i < ans.size(); i++) { printf("%d", Node[ans[i]].weight); if (i != ans.size() - 1)printf(" "); } printf("\n"); return; } if (sum > s)return; for (int i = 0; i < Node[index].child.size(); i++) { int child = Node[index].child[i]; ans.push_back(child); DFS(child, sum + Node[child].weight); ans.pop_back(); } } int main() { scanf("%d%d%d", &n, &m, &s); for (int i = 0; i < n; i++)scanf("%d", &Node[i].weight); while (m--) { int id, k; scanf("%d%d", &id, &k); while (k--) { int idk; scanf("%d", &idk); Node[id].child.push_back(idk); } sort(Node[id].child.begin(), Node[id].child.end(), comp); } ans.push_back(0); DFS(0, Node[0].weight); return 0; }