PAT A1053 Path of Equal Weight ——十年一觉扬州梦

PAT A1053 Path of Equal Weight

  • 通过dfs累加total_weight,如果< amount则继续,如果= amount且为叶节点则输出,其他情况弹出,return
  • 注意dfs的最后一句要有path.pop_back();表示返回上一层之前把自己弹出,否则path里会留下多余的东西
  • 书上是多传了一个参数记录当前层数,则可以按照层数直接放到path数组的对应位置,不必考虑把吃了的再吐出来
  • 每个节点的子节点数组按照weight从大到小排序,则满足序列递减输出的要求
  • 在这里插入图片描述
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <unordered_map>
#include <stack>


using namespace std;


vector<int> weight;
vector<vector<int> > children;
vector<int> path;
int amount = 0;

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

void dfs(int root,int total_weight){
    path.push_back(weight[root]);
    if(total_weight >= amount){
        if(total_weight == amount && children[root].size() == 0){
            for(int i = 0;i < path.size();i ++){
                cout << path[i];
                if(i < path.size() - 1) cout << ' ';
            } 
            cout << endl;
        }
        path.pop_back();
        return;
    }
    for(int i = 0;i < children[root].size();i ++){
        dfs(children[root][i],total_weight + weight[children[root][i]]);
    }
    path.pop_back();
}

#define DEBUG 1


int main(){

#ifdef DEBUG
	freopen("1.txt","r",stdin);	
#endif

    int num,pnum;
    cin >> num >> pnum >> amount;
    children.resize(num);
    for(int i = 0;i < num;i ++){
        int w;
        cin >> w;
        weight.push_back(w);
    }
    for(int i = 0;i < pnum;i ++){
        int p,cnum;
        cin >> p >> cnum;
        for(int j = 0;j < cnum;j ++){
            int child;
            cin >> child;
            children[p].push_back(child);
        }
        sort(children[p].begin(),children[p].end(),cmp);
    }
    int root = 0;
    dfs(root,weight[root]);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值