树的遍历——A1053.Path of Equal Weight(30) 只可DFS不可BFS

Posted jasonpeng1

tags:

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

技术图片

 

 

#include <bits/stdc++.h>
#include <stdio.h>
#include <stdlib.h>
#include <queue>
using namespace std;
const int MAXN = 110;
struct Node{
    int weight;
    vector<int> child;
}Node[MAXN];
bool cmp(int a,int b){
    return Node[a].weight > Node[b].weight;
}
int n,m,S;//结点数,边数及给定的和
int path[MAXN];//记录路径
void DFS(int index,int numNode,int sum){
    if(sum > S){
        return;
    }
    if(sum == S){
        if(Node[index].child.size() != 0){
            return;
        }
        for(int i=0;i<numNode;++i){
            printf("%d",Node[path[i]].weight);
            if(i < numNode-1){
                printf(" ");
            }else{
                printf("
");
            }
        }
        return;
    }
    for(int i=0;i<Node[index].child.size();++i){
        int child = Node[index].child[i];
        path[numNode] = child;
        DFS(child,numNode+1,sum + Node[child].weight);
    }
}
int main(){
    scanf("%d%d%d",&n,&m,&S);
    for(int i=0;i<n;++i){
        scanf("%d",&Node[i].weight);
    }
    int id,k,child;
    for(int i=0;i<m;++i){
        scanf("%d%d",&id,&k);
        for(int j=0;j<k;++j){
            scanf("%d",&child);
            Node[id].child.push_back(child);
        }
        sort(Node[id].child.begin(),Node[id].child.end(),cmp);
    }
    path[0] = 0;//路径的第一个节点设置为0号节点
    DFS(0,1,Node[0].weight);
    system("pause");
    return 0;
}

 

以上是关于树的遍历——A1053.Path of Equal Weight(30) 只可DFS不可BFS的主要内容,如果未能解决你的问题,请参考以下文章

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

1053 Path of Equal Weight (30 分)难度: 一般 / 树的遍历

[PAT] A1053 Path of Equal Weight

1053 Path of Equal Weight

1053 Path of Equal Weight (30分)

PAT甲题题解-1053. Path of Equal Weight (30)-dfs