pat甲级1053

传送门

 

这道题比较简单的30分题吧,题意很好理解输出权值为S的路径的权值。你可以选择从父节点向下遍历,也可以从叶子节点向上遍历。不过需要注意的一点是,输出要按权值从大到小的顺序。所以我选择的从父节点开始遍历,遍历前,先将儿节点按权值排序。另外需要注意输出格式,每行末尾没有空格。

还有学到的一点,关于结构体排序,在我的代码中,是对结构体中的child数组进行的排序,而不是对结构体排序,也即是说对int排序而不是struct,之前我写的cmp函数是这样的

int cmp(node a,node b){
    return a.wei>b.wei;
}

一直报错,类型转换不正确。但是之前一直这样写也没注意,看了别人的博客才发现问题。

下面是正解代码。

#include<iostream>
#include <vector>
#include <cstring>
#include <algorithm>

using namespace std;
struct node{
    int wei;
    vector<int > child;
};


bool isnonleaf[110];
vector<node> fa(110);
vector<int > path;
int n=0,m,S;
bool cmp1(int a,int b){
    return fa[a].wei>fa[b].wei;
}
void dfs(int sum,int s){
    path.push_back(s);
//    sum+=fa[s].wei;
    if(sum+fa[s].wei==S){
        if(!isnonleaf[s]){
            for(int i =0;i<path.size();++i){
                cout<<fa[path[i]].wei;
                if(i!=path.size()-1) cout<<' ';
            }
//        path.clear();
        cout<<endl;
        }
        return;
    }
    else for(int i=0;i<fa[s].child.size();++i){
        dfs(sum+fa[s].wei,fa[s].child[i]);
        path.pop_back();//还原现场
    }
}
int main()
{


    memset(isnonleaf,0,sizeof(isnonleaf));

    cin>>n>>m>>S;
    for(int i=0;i<n;++i) cin>>fa[i].wei;
    for(int i=0;i<m;++i){
        int f,k,c;
        cin>>f>>k;
        isnonleaf[f]=true;
        for(int j=0;j<k;++j){
            cin>>c;
            fa[f].child.push_back(c);
        }
        sort(fa[f].child.begin(),fa[f].child.end(),cmp1);
    }
    dfs(0,0);
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值