1. 关键代码
简单重写了一下DFS,欢迎指正更简便的写法
void DFS(int index, int sum) {
if (Node[index].child.empty()) { //到达孩子结点
if (sum + Node[index].data == S) {
temp.push_back(Node[index].data);
ans[cnt++] = temp;
temp.pop_back();
}
return;
}
if (sum > S) return;
temp.push_back(Node[index].data);
sum += Node[index].data;
for (int i = 0; i < Node[index].child.size(); ++i) {
int id = Node[index].child[i];
DFS(id, sum);
}
temp.pop_back();
}
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 1010;
struct node {
int data;
vector<int> child;
} Node[maxn];
int n, m, S;
vector<int> temp, ans[maxn];
int cnt = 0;
bool cmp(int a, int b) {
return Node[a].data > Node[b].data;
}
void DFS(int index, int sum) {
if (Node[index].child.empty()) { //到达孩子结点
if (sum + Node[index].data == S) {
temp.push_back(Node[index].data);
ans[cnt++] = temp;
temp.pop_back();
}
return;
}
if (sum > S) return;
temp.push_back(Node[index].data);
sum += Node[index].data;
for (int i = 0; i < Node[index].child.size(); ++i) {
int id = Node[index].child[i];
DFS(id, sum);
}
temp.pop_back();
}
int main() {
cin >> n >> m >> S;
for (int i = 0; i < n; ++i) {
cin >> Node[i].data;
}
for (int i = 0; i < m; ++i) {
int id, child, k;
cin >> id >> k;
for (int j = 0; j < k; ++j) {
cin >> child;
Node[id].child.push_back(child);
}
sort(Node[id].child.begin(), Node[id].child.end(), cmp);
}
DFS(0, 0);
for (int i = 0; i < cnt; ++i) {
for (int j = 0; j < ans[i].size(); ++j) {
printf("%d", ans[i][j]);
if (j != ans[i].size() - 1) printf(" ");
}
printf("\n");
}
return 0;
}