鱼C论坛

 找回密码
 立即注册
查看: 2367|回复: 0

[技术交流] PTA A_1053 Path of Equal Weight

[复制链接]
发表于 2020-2-12 12:21:03 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
传送门:https://pintia.cn/problem-sets/9 ... /994805424153280512

解:
多叉树遍历
  1. #include<cstdio>
  2. #include<vector>
  3. #include<algorithm>

  4. using namespace std;

  5. typedef struct node{
  6.     int weight;
  7.     vector<int> children;
  8. } BTNode;

  9. BTNode tree[105];
  10. int total = 0, s;
  11. vector<int> path;
  12. vector< vector<int> > ans;

  13. void pretorder(int root)
  14. {
  15.     int w = tree[root].weight, l = tree[root].children.size();

  16.     path.push_back(w);
  17.     if ((total += w) == s && !l) ans.push_back(path);

  18.     for (int i = 0; i < l; i++)
  19.         pretorder(tree[root].children[i]);

  20.     path.pop_back();
  21.     total -= w;
  22. }

  23. bool cmp(vector<int> a, vector<int> b)
  24. {
  25.     return a > b;
  26. }

  27. int main(void)
  28. {
  29.     int n, m;
  30.     scanf("%d %d %d", &n, &m, &s);
  31.     if (!n) return 0;

  32.     for (int i = 0; i < n; i++)
  33.         scanf("%d", &tree[i].weight);

  34.     while (m--)
  35.     {
  36.         int id, k;

  37.         scanf("%d %d", &id, &k);  
  38.         while (k--)
  39.         {
  40.             int child;

  41.             scanf("%d", &child);
  42.             tree[id].children.push_back(child);
  43.         }
  44.     }
  45.    
  46.     pretorder(0);

  47.     sort(ans.begin(), ans.end(), cmp);

  48.     for (int i = 0; i < ans.size(); i++)
  49.         for (int j = 0; j < ans[i].size(); j++)
  50.         {
  51.             printf("%d", ans[i][j]);
  52.             (j < ans[i].size() - 1) ? putchar(' ') : putchar('\n');
  53.         }
  54.         
  55.     return 0;
  56. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-1 09:28

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表