注意pop的时机,在遍历的时候因为只需要指定路径所以进入别的路径的时候就直接pop就可以了
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 110;
struct node
{
int weight;
int index;
vector<int> child;
}Node[MAXN];
bool vis[MAXN];
vector<int> path;
vector<int> tempPath;
int n,m,needWeight;
bool cmp(int a,int b)
{
return Node[a].weight > Node[b].weight;
}
void DFS(int s,int nowWeight)
{
tempPath.push_back(s);
vis[s] = true;
nowWeight += Node[s].weight;
if(nowWeight > needWeight)
{
return ;
}
if(nowWeight == needWeight )
{
if(Node[s].child.size() == 0)
{
path = tempPath;
for(int i = 0;i<path.size();i++)
{
if(i == 0)
{
printf("%d",Node[path[i]].weight);
}
else
{
printf(" %d",Node[path[i]].weight);
}
}
printf("\n");
return ;
}
else
{
return ;
}
}
for(int i = 0;i<Node[s].child.size();i++)
{
DFS(Node[s].child[i],nowWeight);
tempPath.pop_back(); //执行完就立刻pop掉 防止出现还在里面 影响结果 不需要pop的是前驱
}
}
int main(void)
{
freopen("pat0314/in.txt","r",stdin);
cin>>n>>m>>needWeight;
for(int i = 0;i<n;i++)
{
cin>>Node[i].weight;
}
for(int i = 0;i<m;i++)
{
int root,childNum;
cin>>root>>childNum;
for(int j = 0;j < childNum;j++)
{
int children;
cin>>children;
Node[root].child.push_back(children);
}
sort(Node[root].child.begin(),Node[root].child.end(),cmp);
}
DFS(0,0);
return 0;
}