[PAT] Grade 1053 Path of Equal Weight (30 minutes) (the DFS)

Meaning of the questions:

The number of input nodes of the number of three positive integers N, M, S (N <= 100, M <N, S <= 2 ^ 30) are representative of the number of non-leaf nodes and the need, the value of the next N pieces of positive integers (<1000) representing each node weights input next M rows, each row comprising a number representative of a non-leaf nodes of the two numbers and the number x represents a number of its children nodes a number, then enter the digits x indicates the number of child nodes. Nonincreasing order output path to the right from the root node to a leaf weight, which is equal to S.

Code:

#define HAVE_STRUCT_TIMESPEC
#include<bits/stdc++.h>
using namespace std;
int w[107];
vector<int>v[107];
int s;
int now;
vector<int>path;
int flag;
int vis[107];
vector<int>ans[107];
int cnt;
int dfs(int x){
path.push_back(w[x]);
now+=w[x];
if(now==s){
if(!vis[x])
ans[++cnt]=path;
path.pop_back();
now-=w[x];
return 0;
}
else if(now>s){
path.pop_back();
now-=w[x];
return 0;
}
else
for(auto it:v[x])
dfs(it);
path.pop_back();
now-=w[x];
return 0;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n,m;
cin>>n>>m>>s;
for(int i=0;i<n;++i)
cin>>w[i];
for(int i=1;i<=m;++i){
string fa;
cin>>fa;
int f=(fa[0]-'0')*10+fa[1]-'0';
vis[f]=1;
int x;
cin>>x;
string son;
for(int j=1;j<=x;++j){
cin>>son;
int s=(son[0]-'0')*10+son[1]-'0';
v[f].push_back(s);
}
}
dfs(0);
sort(ans+1,ans+1+cnt);
for(int i=cnt;i;--i){
if(i<cnt)
cout<<"\n";
cout << years [i] [0];
for(int j=1;j<ans[i].size();++j)
cout<<" "<<ans[i][j];
}
return 0;
}

Guess you like

Origin www.cnblogs.com/ldudxy/p/11627855.html