A1053 Path of Equal Weight [dfs]

在这里插入图片描述

#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<algorithm>
using namespace std;
const int maxn = 110;
struct node
{
	int weight;
	vector<int>child;
}Node[maxn];
bool cmp(int a, int b)
{
	return Node[a].weight > Node[b].weight;
}
int n, m, s;
int path[maxn];

void dfs(int index, int nowcount, int sum)
{
	if (sum > s)
		return;
	if (sum == s)
	{
		if (Node[index].child.size() != 0)
			return;
		for (int i = 0; i < nowcount; i++)
		{
			cout << Node[path[i]].weight;
			if (i < nowcount - 1)
				cout << " ";
			else
				cout << endl;
		}
		return;
	}
	for (int i = 0; i < Node[index].child.size(); i++)
	{
		int child = Node[index].child[i];
		path[nowcount] = child;
		dfs(child, nowcount + 1, sum + Node[child].weight);
	}
}
int main()
{
	cin >> n >> m >> s;
	for (int i = 0; i < n; i++)
	{
		cin >> Node[i].weight;
	}
	int id, childnum, child;
	for (int i = 0; i < m; i++)
	{
		cin >> id >> childnum;
		for (int j = 0; j < childnum; j++)
		{
			cin >> child;
			Node[id].child.push_back(child);
		}
		sort(Node[id].child.begin(), Node[id].child.end(), cmp);
	}
	path[0] = 0;
	dfs(0,1,Node[0].weight);
}

原文地址:https://www.cnblogs.com/Hsiung123/p/13812014.html