题目介绍
题意:给一个树,根为1 ,输出从根到叶子的权值和=m的所有路径(顺序有要求)
思路:dfs…保存路径 然后从叶子往回找
代码
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define mp make_pair
const int N= 1003;
vector<int>V[N];
int w[N];
int noleft[N];
int path[N];
int ww[N];
void dfs(int t){
for(int i=0;i<V[t].size();++i){
w[V[t][i]] +=w[t];
path[V[t][i]] = t;
dfs(V[t][i]);
}
}
int main(){
int n,m,s;
cin>>n>>m>>s;
for(int i=0;i<n;++i)cin>>w[i],ww[i]=w[i];
for(int i=0;i<m;++i){
int x,k,y;
scanf("%d %d",&x,&k);
noleft[x]=1;
while(k--){
scanf("%d",&y);
V[x].push_back(y);
}
}
dfs(0);
vector< vector<int> >ans;
for(int i=0;i<n;++i){
if(noleft[i]==0 && w[i]==s){
vector<int>tmp;
int ind = i;
while(ind){
tmp.push_back(ww[ind]);
ind = path[ind];
}
tmp.push_back(ww[ind]);
reverse(tmp.begin(),tmp.end());
ans.push_back(tmp);
}
}
sort(ans.begin(),ans.end());
for(int i=ans.size()-1;i>=0;--i){
vector<int>tmp =ans[i];
for(int j=0;j<tmp.size();++j){
printf("%d%c",tmp[j],j==tmp.size()-1?'\n':' ');
}
}
return 0;
}