pat甲级1053

二叉树的静态实现。
深度优先遍历,在每一个多叉点,逐个进入下层递归,return时要注意还原一步,到初始状态

#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

struct node{
    int weight;
    vector<int> child;
} tree[100];

int N, M, S;
vector<int> path;

bool cmp(int a, int b);
void DFS(int index, int sum);

int main(){
    scanf("%d%d%d", &N, &M, &S);
    for(int i=0; i<N; i++) scanf("%d", &tree[i].weight);
    while(M--){
        int n, ct, ch;
        scanf("%d%d", &n, &ct);
        while(ct--){
            scanf("%d", &ch);
            tree[n].child.push_back(ch);
        }
        //子结点按权重从大到小排,即可满足序列输出顺序的要求
        sort(tree[n].child.begin(), tree[n].child.end(), cmp);
    }
    path.push_back(tree[0].weight);
    DFS(0, tree[0].weight);

    return 0;
}

bool cmp(int a, int b){
    return tree[a].weight>tree[b].weight;
}

//深度遍历到index结点,至此积累了sum的权重
void DFS(int index, int sum){
    if(tree[index].child.size()==0){
        if(sum==S){
            int c = path.size();
            for(int i=0; i<c; i++){
                printf("%d", path[i]);
                if(i<c-1) printf(" ");
            }
            printf("\n");
            return;
        }
        else return;
    }
    else{
        if(sum>=S) return; //剪枝,如果内部结点处sum已到达阈值,直接返回
        else{
            int ch_c = tree[index].child.size();
            for(int i=0; i<ch_c; i++){
                int t = tree[index].child[i];
                int w = tree[t].weight;
                path.push_back(w);
                DFS(t, sum+w);
                path.pop_back(); //退回到初始状态,走另外几条路
            }
        }
    }
    return;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值