一、题目描述
Input Specification:
Output Specification:
Sample Input:
20 9 24
10 2 4 3 5 10 2 18 9 7 2 2 1 3 12 1 8 6 2 2
00 4 01 02 03 04
02 1 05
04 2 06 07
03 3 11 12 13
06 1 09
07 2 08 10
16 1 15
13 3 14 16 17
17 2 18 19
Sample Output:
10 5 2 7
10 4 10
10 3 3 6 2
10 3 3 6 2
二、解题思路
这道题考了DFS以及树的相关知识。显然,题目所给是一个带点权的树,让我们求出总权重为题目所给值的路线,我们可以用一个数组path存放路径中的各个节点,对于DFS,我们要输入的参数有现在操作的节点的编号,之前搜索过的节点数,还有目前的点权总和。如果当前点权总和已经比题目给的数大,则直接return,如果小于,则对当前节点的每个孩子进行一次DFS,由于题目要求按照路径从大到小输出,所以孩子节点也要按照点权从大到小进行排序。如果恰好等于题目给的数,则先判断当前节点是否为叶子节点,如果不是,则return,如果是,那么我们就可以进行输出。
三、AC代码
#include<cstdio>
#include<vector>
#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 idx, int numNode, int sum)
{
if(sum > s) return;
if(sum == s)
{
if(node[idx].child.size() != 0) return;
for(int i=0; i<numNode; i++)
{
printf("%d", node[path[i]].weight);
if(i < numNode-1) printf(" ");
else printf("\n");
}
return;
}
for(int i=0; i<node[idx].child.size(); i++)
{
int child = node[idx].child[i];
path[numNode] = child;
DFS(child, numNode+1, sum+node[child].weight);
}
}
int main()
{
scanf("%d%d%d", &n, &m, &s);
for(int i=0; i<n; i++)
scanf("%d", &node[i].weight);
int id, k, child;
for(int i=0; i<m; i++)
{
scanf("%d%d", &id, &k);
for(int j=0; j<k; j++)
{
scanf("%d", &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);
return 0;
}