PAT(Advance)1053. Path of Equal Weight
该题分制为30分。
题目链接https://pintia.cn/problem-sets/994805342720868352/problems/994805424153280512
题目要求输出所有权值和为S的路径,并且一定是从根节点到叶子结点的,输出的时候需要给序列从大到小排序。第一次我用的广搜路径出来了,但是顺序不对,而且代码量也比深搜多,所以还是放弃用广搜了。下面代码是参考柳婼大神的代码。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 110;
struct Node
{
int w;
vector<int>children;
};
vector<Node>tree;
int path[maxn];
int n, m, s;
void DFS(int index, int depth, int sum)
{
if (sum > s)
return;
if (sum == s)
{
if (tree[index].children.size() != 0)
return;
for (int i = 0; i < depth; i++)
{
cout << tree[path[i]].w;
if (i < depth - 1)
cout << " ";
}
cout << endl;
return;
}
for (int i = 0; i < tree[index].children.size(); i++)
{
int node = tree[index].children[i];
path[depth] = node;
DFS(node, depth+1, sum + tree[node].w);
}
}
bool cmp(int a, int b)
{
return tree[a].w > tree[b].w;
}
int main()
{
cin >> n >> m >> s;
tree.resize(n);
for (int i = 0; i < n; i++)
{
cin >> tree[i].w;
}
for (int i = 0; i < m; i++)
{
int index, k;
cin >> index >> k;
for (int j = 0; j < k; j++)
{
int temp;
cin >> temp;
tree[index].children.push_back(temp);
}
sort(tree[index].children.begin(), tree[index].children.end(), cmp);
}
DFS(0, 1, tree[0].w);
return 0;
}