数据结构
- 静态树。树中有权值以及vector型的孩子。
- vector来放孩子。
- hashpath数组。用来放置路径
算法
- 使用DFS(),来遍历这棵树。如果参数中的sum,等于题目要求的weight值,同时该节点没有孩子了,就一次输出。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <stdio.h>
#include <math.h>
#include <queue>
#include <stack>
#include <cstring>
#include <cmath>
using namespace std;
int hashset[100];
int w;
struct node
{
int weight;
vector<int> child;
} Node[100];
void DFS(int root,int numofNode,int sum)
{
if(sum==w)
{
if(Node[root].child.size()>0)
{
return;
}
else
{
for(int i=0; i<numofNode; i++)
{
printf("%d",Node[hashset[i]].weight);
if (i<numofNode-1)
{
printf(" ");
}
else
{
printf("\n");
}
}
return;
}
}
if(sum>w)
return;
for(int i=0; i<Node[root].child.size(); i++)
{
int child;
child=Node[root].child[i];
hashset[numofNode]=child;
DFS(child,numofNode+1,sum+Node[child].weight);
}
}
bool cmp(int a,int b)
{
return Node[a].weight>Node[b].weight;
}
int main()
{
int num;
int n;
scanf("%d%d%d",&num,&n,&w);
for(int i=0; i<num; i++)
{
scanf("%d",&Node[i].weight);
}
for(int i=0; i<n; i++)
{
int id,k;
scanf("%d %d",&id,&k);
for(int j=0; j<k; j++)
{
int x;
scanf("%d",&x);
Node[id].child.push_back(x);
}
sort(Node[id].child.begin(),Node[id].child.end(),cmp);
}
DFS(0,1,Node[0].weight);
}