1. 程式人生 > 其它 >PAT 甲級 1053 Path of Equal Weight (30 分)

PAT 甲級 1053 Path of Equal Weight (30 分)

技術標籤:PAT-Advancedc++

Note

  • 樹的遍歷 – DFS
  • 輸入完孩子結點就排序~

Code

#include<bits/stdc++.h>
using namespace std;

int S,ind=0;
vector<int> tmp,ans[1000];

struct node{
	int weight;
	vector<int> child;
}tree[110];

bool cmp(int a,int b){
	return tree[a].weight>tree[b].weight;
}

//bool cmp(vector<int> a,vector<int> b){
// int lena=a.size(),lenb=b.size(); // int i=1; // while(i<lena&&i<lenb){ // if(a[i]>b[i]) return a[i]>b[i]; // i++; // } // return a.size()<b.size(); //} void dfs(int root,int sum){ if(sum>S) return ; else if(sum==S&&tree[root].child.empty()){ for(int i=0;i<tmp.size();i++
) ans[ind].push_back(tmp[i]); ind++; return ; } for(int i=0;i<tree[root].child.size();i++){ sum+=tree[tree[root].child[i]].weight; tmp.push_back(tree[tree[root].child[i]].weight); dfs(tree[root].child[i],sum); sum-=tree[tree[root].child[i]].weight; tmp.pop_back(); } return ; }
int main(){ #ifndef ONLINE_JUDGE freopen("data.txt","r",stdin); #endif int n,m,w; scanf("%d %d %d",&n,&m,&S); for(int i=0;i<n;i++){ scanf("%d",&w); tree[i].weight=w; } int id,k,ch; for(int i=0;i<m;i++){ scanf("%d %d",&id,&k); for(int j=0;j<k;j++){ scanf("%d",&ch); tree[id].child.push_back(ch); } //here sort!!! sort(tree[id].child.begin(),tree[id].child.end(),cmp); } tmp.push_back(tree[0].weight); dfs(0,tree[0].weight); for(int i=0;i<ind;i++){ for(int j=0;j<ans[i].size();j++){ if(j!=0) printf(" "); printf("%d",ans[i][j]); } printf("\n"); } return 0; }