1053 Path of Equal Weight (30 分)(树的遍历)

Posted chenchen-12

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1053 Path of Equal Weight (30 分)(树的遍历)相关的知识,希望对你有一定的参考价值。

题目大意:给出树的结构和权值,找从根结点到叶子结点的路径上的权值相加之和等于给定目标数的路径,并且从大到小输出路径

#include<bits/stdc++.h>

using namespace std;
int n,m,sum;
const int N=120;
struct node
{
    int w;
    vector<int>p;
}tree[N];
bool cmp(int a,int b)
{
    return tree[a].w>tree[b].w;
}
vector<int>path;
void dfs(int s,int v)
{
    //cout<<s<<"  "<<v<<endl;
    if(s>sum) return;
    if(s==sum){
        if(tree[v].p.size()!=0) return;
        path.push_back(v);
        for(int i=0;i<path.size();i++){
            if(i) printf(" ");
            printf("%d",tree[path[i]].w);
        }
        printf("
");
        path.pop_back();
    }
    path.push_back(v);
    for(int i=0;i<tree[v].p.size();i++){
        dfs(s+tree[tree[v].p[i]].w,tree[v].p[i]);
    }
    path.pop_back();
}
int main()
{
    scanf("%d %d %d",&n,&m,&sum);
    for(int i=0;i<n;i++) scanf("%d",&tree[i].w);
    for(int i=0;i<m;i++){
        int id;
        int k;
        scanf("%d %d",&id,&k);
        for(int j=0;j<k;j++){
            int x;
            scanf("%d",&x);
            tree[id].p.push_back(x);
        }
        sort(tree[id].p.begin(),tree[id].p.end(),cmp);
    }
    dfs(tree[0].w,0);
    return 0;
}

 

以上是关于1053 Path of Equal Weight (30 分)(树的遍历)的主要内容,如果未能解决你的问题,请参考以下文章

PAT 1053. Path of Equal Weight

PAT 1053 Path of Equal Weight (30)

1053 Path of Equal Weight

1053 Path of Equal Weight

PAT 1053. Path of Equal Weight (30)

PAT Advanced Level 1053 Path of Equal Weight