题目地址:https://pintia.cn/problem-sets/994805342720868352/problems/994805424153280512
#include <iostream>
#include <string>
#include <set>
#include <map>
#include<queue>
#include<stack>
#include<algorithm>
//new and delete
//A1053 Path of Equal Weight
using namespace std;
typedef int ElemType;
const int MaxN = 120;
struct node {
ElemType w; //weight
vector<int> child;
}Node[MaxN];
bool cmp(int child1,int child2) {
//权值大的孩子排在前面
return Node[child1].w > Node[child2].w;
}
vector<int>temp; //路径暂存
//从root开始递归访问,得到路径序号temp,存储到ans(注意加引用)
void DFS(int S, vector<vector<int> > &ans,int w_sum,int root) {
w_sum += Node[root].w;
//cout << w_sum << endl;
//cout << "root:" << root << endl;
if (w_sum > S )
return;
temp.push_back(root);
//得到一条路径
if (w_sum == S && Node[root].child.empty()) {
ans.push_back(temp);
temp.pop_back();
return;
}
//递归访问孩子,这里从右往左
if (!Node[root].child.empty()) {
vector<int>::iterator it = Node[root].child.begin();
sort(it, Node[root].child.end(), cmp);
for (it= Node[root].child.begin(); it!= Node[root].child.end(); it++)
DFS(S, ans, w_sum, *it);
}
temp.pop_back();
return;
}
int main() {
//freopen( "input.txt", "r", stdin);
//N:the number of nodes in a tree
//M:the number of non-leaf nodes
//S:the given weight number
int N, M, S;
//data input
cin >> N >> M >> S;
for (int i = 0; i < N; i++)
cin >> Node[i].w;
for (int i = 0; i < M; i++) {
int index,child_num;
cin >> index >> child_num;
for (int j = 0; j < child_num; j++) {
int child_1;
cin >> child_1;
Node[index].child.push_back(child_1);
}
}
vector<vector<int> > ans; //存储符合条件的序列
DFS(S, ans, 0, 0);
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans[i].size(); j++) {
cout << Node[ans[i][j]].w;
if (j == ans[i].size() - 1)
cout << endl;
else
cout << " ";
}
}
return 0;
}