#include<bits/stdc++.h>
using namespace std;
struct Node{
int id;
vector<int> child;
int weight;
}node[110];
int n,m,s;
int path[110];
bool cmp(int a,int b){
return node[a].weight>node[b].weight;
}
void dfs(int root,int nodenum,int tempvalue){
if(tempvalue>s) return;
if(tempvalue==s){
if(node[root].child.size()==0){
for(int i=0;i<nodenum;i++){
if(i==0) cout<<node[path[i]].weight;
else cout<<' '<<node[path[i]].weight;
}
cout<<endl;
}else{
return;
}
}
for(int i=0;i<node[root].child.size();i++){
path[nodenum]=node[root].child[i];
dfs(node[root].child[i],nodenum+1,tempvalue+node[node[root].child[i]].weight);
}
}
int main()
{
freopen("in.txt","r",stdin);
cin>>n>>m>>s;
for(int i=0;i<n;i++){
int temp;cin>>temp;
node[i].id=i;
node[i].weight=temp;
}
for(int i=0;i<m;i++){
int root,k;cin>>root>>k;
for(int j=0;j<k;j++){
node[root].child.resize(k);
cin>>node[root].child[j];
}
sort(node[root].child.begin(),node[root].child.end(),cmp);
}
path[0]=0;
dfs(0,1,node[0].weight);
return 0;
}
另一段AC代码
#include<bits/stdc++.h>
using namespace std;
const int MAXN=110;
struct Node{
int weight;
vector<int> child;
}node[MAXN];
int n,m,s;
vector<int> temp;
bool cmp(int a,int b){
return node[a].weight>node[b].weight;
}
void dfs(int root,int sum){
if(node[root].child.size()==0){
sum=sum+node[root].weight;
temp.push_back(node[root].weight);
if(sum==s){
for(int i=0;i<temp.size();i++){
if(i==0) cout<<temp[i];
else cout<<' '<<temp[i];
}
cout<<endl;
temp.pop_back();
return;
}else{
temp.pop_back();
return;
}
}
for(int i=0;i<node[root].child.size();i++){
temp.push_back(node[root].weight);
dfs(node[root].child[i],sum+node[root].weight);
temp.pop_back();
}
}
int main()
{
freopen("in.txt","r",stdin);
cin>>n>>m>>s;
for(int i=0;i<n;i++){
cin>>node[i].weight;
}
for(int i=0;i<m;i++){
int root,k;cin>>root>>k;
for(int j=0;j<k;j++){
int temp;cin>>temp;
node[root].child.push_back(temp);
}
sort(node[root].child.begin(),node[root].child.end(),cmp);
}
dfs(0,0);
return 0;
}