给出n个节点的树,m个非叶子节点,求从根节点到叶子节点的权值等于s的路径,并把其权值从根节点到叶子节点输出,如果有多条,按非递增顺序输出,(序列{
A
1
,
A
2
,
A
3
,
.
.
.
,
A
n
A_1,A_2,A_3,...,A_n
A1,A2,A3,...,An}大于序列{
B
1
,
B
2
,
B
3
,
.
.
,
A
m
B_1,B_2,B_3,..,A_m
B1,B2,B3,..,Am},存在1
≤
\leq
≤k
<
<
<min(n,m),对于i到k,
A
i
=
B
i
A_i=B_i
Ai=Bi且
A
k
+
1
>
B
k
+
1
A_{k+1} >B_{k+1}
Ak+1>Bk+1)。
先对每一个非叶子节点保存其子节点,并按权值从大到小排序,用深度优先搜索遍历路径求和,然后输出路径权值即为结果。
(用时:27:51.19)
#include <bits/stdc++.h>
using namespace std;
vector<int> weight;
int s = 0;
queue<vector<int> > pathQue;
bool cmp(int a,int b)
{
return weight[a]>weight[b];
}
void dfs(int index,vector<int> tree[],int sum,vector<int> path)
{
if(tree[index].size()==0) {
if(sum==s) {
for(int i=0; i<path.size(); i++) {
if(i==0) {
printf("%d",weight[path[i]]);
} else {
printf(" %d",weight[path[i]]);
}
}
printf("\n");
}
return;
}
for(int i=0; i<tree[index].size(); i++) {
if(sum+weight[tree[index][i]]<=s) {
path.push_back(tree[index][i]);
dfs(tree[index][i],tree,sum+weight[tree[index][i]],path);
path.pop_back();
}
}
}
int main()
{
int n,m,t;
scanf("%d%d%d",&n,&m,&s);
for(int i=0; i<n; i++) {
scanf("%d",&t);
weight.push_back(t);
}
vector<int> tree[n];
int k,nodeIndex;
for(int i=0; i<m; i++) {
scanf("%d%d",&nodeIndex,&k);
for(int j=0; j<k; j++) {
scanf("%d",&t);
tree[nodeIndex].push_back(t);
}
sort(tree[nodeIndex].begin(),tree[nodeIndex].end(),cmp);
}
vector<int> path;
path.push_back(0);
dfs(0, tree,weight[0],path);
return 0;
}