UVa 548 -- Tree
阿新 • • 發佈:2018-02-15
ont 遞歸 end font 當前 node cst space !=
UVa 548 - Tree
給你一棵樹的中根序和後根序遍歷,求從根到葉子組成的路徑中數字和最小的那條。
分析:DFS,樹,遞歸。直接遞歸求解,用全局變量更新即可。
1 #include<iostream> 2 #include<cstdio> 3 #include<sstream> 4 #include<cstring> 5 using namespace std; 6 const int maxn = 10000 + 5; 7 int in_list[maxn];///中序序列 8 int post_list[maxn];///後序序列 9int ans; 10 int ans_node; 11 int list_len; 12 ///按行讀取輸入結點序列 13 bool read_list(int *a) 14 { 15 string line; 16 if(!getline(cin,line)) return false; 17 stringstream ss(line); 18 int n=0; 19 int x; 20 while(ss >> x) a[n++] = x; 21 list_len = n; 22 return n > 0; 23 } 2425 void bfs(int *in,int *post,int n,int sum) 26 { 27 if(n <= 0) return; 28 if(n == 1)///到達葉子節點 29 { 30 ///更新解 31 if(ans > sum+post[n-1]) 32 { 33 ans = sum+post[n-1];ans_node = post[n-1]; 34 } 35 ///相等的情況 36 else if(ans == sum+post[n-1] && post[n-1]<ans_node) 37 { 38 ans = sum+post[n-1];ans_node = post[n-1]; 39 } 40 return; 41 } 42 int root = post[n-1]; 43 int p = 0; 44 while(in[p] != root) p++; 45 //進入子樹之前sum加上當前根節點的值 46 sum += root; 47 bfs(in,post,p,sum);///左子樹 48 bfs(in+p+1,post+p,n-p-1,sum);///右子樹 49 } 50 51 int main() 52 { 53 while(read_list(in_list)) 54 { 55 read_list(post_list); 56 ans = 100000005;ans_node = 20000; 57 bfs(in_list,post_list,list_len,0); 58 cout<<ans_node<<endl; 59 } 60 return 0; 61 }
UVa 548 -- Tree