题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805424153280512

这题说不复杂也有点复杂,说复杂也不是很复杂
注意点

  1. 0结点是树根
  2. 孩子结点使用vector数组存储节省空间
  3. 使用sort根据权值对孩子结点进行排序,这样就可以使权值大的先遍历到,使输出符合权值递减
  4. 最精髓的是第33行代码,一开始我用的是push_back,导致错误,这题应该直接覆盖对应数组单位
  5. 记一下DFS的格式
  1. void DFS(int root, int path_num, int sum){

代码

  1. #include<iostream>
  2. #include<vector>
  3. #include<algorithm>
  4. using namespace std;
  5. const int maxn = 110;
  6. int n, m, s;//n是结点总数,m是非叶子结点数量,s是待求的权值和
  7. int weight[maxn];
  8. vector<int> path(maxn);
  9. struct Node{
  10. int data, weight;
  11. vector<int> child;
  12. }node[maxn];
  13. bool cmp(int a, int b){
  14. return node[a].weight > node[b].weight;
  15. }
  16. void DFS(int root, int path_num, int sum){
  17. if(sum > s) return;
  18. if(sum == s){//这个时候说明到达了叶子结点
  19. if(sum == s && node[root].child.size() != 0) return;
  20. for(int i = 0; i < path_num; i++){
  21. printf("%d",node[path[i]].weight);
  22. if(i != path_num - 1) printf(" ");
  23. }
  24. printf("\n");
  25. return;
  26. }
  27. for(int i = 0; i < node[root].child.size(); i++){
  28. int child = node[root].child[i];
  29. path[path_num] = child;
  30. DFS(child, path_num + 1, sum + node[child].weight);
  31. }
  32. }
  33. int main(){
  34. scanf("%d%d%d", &n, &m, &s);
  35. for(int i = 0; i < n; i++) scanf("%d", &node[i].weight);
  36. int tempi, leafnum,temp;
  37. for(int i = 0; i < m; i++){
  38. scanf("%d%d",&tempi, &leafnum);
  39. for(int j = 0; j < leafnum; j++){
  40. scanf("%d",&temp);
  41. node[tempi].child.push_back(temp);
  42. }
  43. sort(node[tempi].child.begin(), node[tempi].child.end(), cmp);
  44. }
  45. path.push_back(0);
  46. DFS(0, 1, node[0].weight);
  47. return 0;
  48. }