example1
- https://pintia.cn/problem-sets/994805342720868352/problems/994805424153280512
#include<iostream>
#include<algorithm>
#include<vector>
#define maxSize 100
using namespace std;
int flag = 0;//输出的时候,0代表还没有输出,所以前面不用加endl
typedef struct {
int weight;
int childrenList[maxSize];
int childrenNum;
}Tree;
Tree tree[maxSize];//这里设置为全局变量是因为cmp需要
bool cmp(const int a, const int b) {
return tree[a].weight > tree[b].weight;
}
void DFS(Tree tree[], int givenWeightNumber, int root, int sum, vector<int>& roads) {
roads.push_back(tree[root].weight);
sum += tree[root].weight;
if (sum == givenWeightNumber) {
if (tree[root].childrenNum != 0) {
//路径权值正好够,但是还没有到叶子节点
return;
}
//可以输出了
for (int i = 0; i < roads.size(); ++i) {
if (i == 0) {
if (flag == 0) {
flag = 1;
}
else {
cout << endl;
}
cout << roads.at(i);
}
else {
cout << " " << roads.at(i);
}
}
}
else {
for (int i = 0; i < tree[root].childrenNum; ++i) {
DFS(tree, givenWeightNumber, tree[root].childrenList[i], sum, roads);
roads.pop_back();
}
}
}
int main() {
int nodesNum;
int nonLeafNodesNum;
int givenWeightNumber;
cin >> nodesNum >> nonLeafNodesNum >> givenWeightNumber;
for (int i = 0; i < maxSize; ++i) {
tree[i].childrenNum = 0;//初始化为0
}
for (int i = 0; i < nodesNum; ++i) {
cin >> tree[i].weight;
}
for (int i = 0; i < nonLeafNodesNum; ++i) {
int id;
int childrenNum;
cin >> id >> childrenNum;
tree[id].childrenNum = childrenNum;
for (int j = 0; j < childrenNum; ++j) {
cin >> tree[id].childrenList[j];
}
sort(tree[id].childrenList, tree[id].childrenList + childrenNum,cmp);//排序,以便于最后输出按从大到小
}//输入完毕
vector<int> roads;
DFS(tree, givenWeightNumber, 0, 0, roads);
return 0;
}