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;
}