PAT1053
1 #include<iostream> 2 #include<vector> 3 #include<stack> 4 #include<algorithm> 5 #include<iterator> 6 using namespace std; 7 8 #define MAX 9999 9 10 void record(stack<int> st, vector<vector<int>> &paths) 11 { 12 vector<int> p; 13 while(!st.empty()) 14 { 15 p.push_back(st.top()); 16 st.pop(); 17 } 18 reverse(p.begin(), p.end()); 19 paths.push_back(p); 20 } 21 22 void DFS_visit(vector<vector<int>> &tree, int S, int start, 23 vector<vector<int>> &paths, stack<int> &st, int sum, vector<int> &weight) 24 { 25 st.push(weight[start]); 26 sum += weight[start]; 27 /*累计权重小于等于S进入判断下一个DFS, 28 若大于则不用后续DFS*/ 29 if(sum <= S) 30 { 31 /*判断是否是叶子结点*/ 32 bool flag(false); 33 for(int i=0; i<tree.size(); ++i) 34 if(tree[start][i] != MAX) 35 { 36 DFS_visit(tree, S, i, paths, st, sum, weight); 37 flag = true; 38 } 39 if(flag == false) 40 if(sum == S) 41 record(st, paths); 42 } 43 sum -= st.top(); 44 st.pop(); 45 } 46 47 void DFS_version(vector<vector<int>> &tree, int S, int start, 48 vector<vector<int>> &paths, vector<int> &weight) 49 { 50 stack<int> st; 51 /*记录累加权重*/ 52 int sum(0); 53 DFS_visit(tree, S, start, paths, st, sum, weight); 54 } 55 56 bool comp(vector<int> v1, vector<int> v2) 57 { 58 if(v1 == v2) 59 return false; 60 vector<int>::iterator iter_v1 = v1.begin(); 61 vector<int>::iterator iter_v2 = v2.begin(); 62 while(1) 63 if((*iter_v1) > (*iter_v2)) 64 return true; 65 else if((*iter_v1) < (*iter_v2)) 66 return false; 67 else 68 {++iter_v1; ++iter_v2;} 69 } 70 71 int main() 72 { 73 int N, M, S; 74 while(cin>>N>>M>>S) 75 { 76 vector<int> colum(N, MAX); 77 /*存成有向图*/ 78 vector<vector<int>> tree(N, colum); 79 vector<int> weight(N, 0); 80 for(int i=0; i<N; ++i) 81 cin>>weight[i]; 82 for(int i=0; i<M; ++i) 83 { 84 int id, k; cin>>id>>k; 85 for(int j=0; j<k; ++j) 86 { 87 int n; cin>>n; 88 tree[id][n] = 1; 89 } 90 } 91 /*存储结果路径*/ 92 vector<vector<int>> paths; 93 DFS_version(tree, S, 0, paths, weight); 94 sort(paths.begin(), paths.end(), comp); 95 for(int i=0; i<paths.size(); ++i) 96 { 97 for(int j=0; j<paths[i].size()-1; ++j) 98 cout<<paths[i][j]<<" "; 99 cout<<paths[i][paths[i].size()-1]<<endl; 100 } 101 } 102 return 0; 103 }
题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1053
思路; 将树存成有向图,用DFS,配一个栈记录路径,最后对多条结果路径排序下,比较简单!