PAT甲级题解 1053

注意pop的时机,在遍历的时候因为只需要指定路径所以进入别的路径的时候就直接pop就可以了

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 110;
struct node
{
    int weight;
    int index;
    vector<int> child;
}Node[MAXN];
bool vis[MAXN];
vector<int> path;
vector<int> tempPath;
int n,m,needWeight;
bool cmp(int a,int b)
{
    return Node[a].weight > Node[b].weight;
}
void DFS(int s,int nowWeight)
{
    tempPath.push_back(s);
    vis[s] = true;
    nowWeight += Node[s].weight;

    if(nowWeight > needWeight)
    {
        return ;
    }
    if(nowWeight == needWeight )
    {
        if(Node[s].child.size() == 0)
        {        
            path = tempPath;
            for(int i = 0;i<path.size();i++)
            {
                if(i == 0)
                {
                    printf("%d",Node[path[i]].weight);
                }
                else
                {
                    printf(" %d",Node[path[i]].weight);
                }
            }
            printf("\n");
            return ;
        }
        else
        {
            return ;
        }


    }
    
    for(int i = 0;i<Node[s].child.size();i++)
    {
        DFS(Node[s].child[i],nowWeight);
        tempPath.pop_back(); //执行完就立刻pop掉 防止出现还在里面 影响结果 不需要pop的是前驱
    }



}
int main(void)
{    
    freopen("pat0314/in.txt","r",stdin);
    cin>>n>>m>>needWeight;
    for(int i = 0;i<n;i++)
    {
        cin>>Node[i].weight;
    }
    for(int i = 0;i<m;i++)
    {
        int root,childNum;
        cin>>root>>childNum;
        for(int j = 0;j < childNum;j++)
        {
            int children;
            cin>>children;
            Node[root].child.push_back(children);

        }
        sort(Node[root].child.begin(),Node[root].child.end(),cmp);
    }
    DFS(0,0);


    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值