方便输出的一点操作:将子节点根据weight来排序,这样遍历到符合要求的路径就可以直接输出!
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<stack>
using namespace std;
const int maxn=105;
int n,m,s;
class node
{
public:
int cnt,flag;
int son[maxn];
};
node g[maxn];
int weight[maxn];
int cmp(const void *a,const void *b)
{
int *c=(int *)a;
int *d=(int *)b;
return weight[*d]-weight[*c]; // 根据weight排序
}
void init()
{
int i,j,u;
scanf("%d%d%d",&n,&m,&s);
for(i=0;i<n;i++) {
scanf("%d",&weight[i]);
g[i].flag =1; //初始化为叶节点
g[i].cnt =0;
}
for(i=0;i<m;i++) {
scanf("%d",&u);
scanf("%d",&g[u].cnt );
if(g[u].cnt >0) g[u].flag =0; //标记为非叶节点
for(j=0;j<g[u].cnt ;j++)
scanf("%d",&g[u].son [j]);
qsort(g[u].son ,g[u].cnt ,sizeof(g[u].son [0]),cmp);
}
}
int pre[maxn];
void dfs(int u,int w)
{
int v,i,j;
if(g[u].flag &&w==s) {
stack<int > sta;
j=u;
while(pre[j]!=-1) {
sta.push (j);
j=pre[j];
}
sta.push (0);
printf("%d",weight[sta.top ()]);sta.pop ();
while(!sta.empty ()){
printf(" %d",weight[sta.top ()]),sta.pop ();
}
printf("\n");
return ;
}
for(i=0;i<g[u].cnt ;i++){
v=g[u].son [i];
pre[v]=u;
int now_weight=w+weight[v];
if(now_weight>s) continue;
dfs(v,now_weight);
}
}
void solve()
{
int i;
pre[0]=-1;
dfs(0,weight[0]);
}
int main()
{
init();
solve();
return 0;
}