PAT(Advance)1053. Path of Equal Weight

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值