标签:des style blog http io ar color os sp
Tree |
You are to determine the value of the leaf node in a given binary tree that is the terminal node of a path of least value from the root of the binary tree to any leaf. The value of a path is the sum of values of nodes along that path.
The input file will contain a description of the binary tree given as the inorder and postorder traversal sequences of that tree. Your program will read two line (until end of file) from the input file. The first line will contain the sequence of values associated with an inorder traversal of the tree and the second line will contain the sequence of values associated with a postorder traversal of the tree. All values will be different, greater than zero and less than 10000. You may assume that no binary tree will have more than 10000 nodes or less than 1 node.
For each tree description you should output the value of the leaf node of a path of least value. In the case of multiple paths of least value you should pick the one with the least value on the terminal node.
3 2 1 4 5 7 6 3 1 2 5 6 7 4 7 8 11 3 5 16 12 18 8 3 11 7 16 18 12 5 255 255
1 3 255
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <sstream> 5 #include <climits> 6 7 using namespace std; 8 9 int mini,min_child; 10 11 int find(int n,int* a, int b) { 12 for (int i = 0;i < n;i++) { 13 if (a[i] == b) return i; 14 } 15 return 0; 16 } 17 18 int tree(int n,int* a,int* b,int sum) { 19 if (n <= 0) return 0; 20 int p = find(n,a,b[n - 1]); 21 sum += b[n - 1]; 22 int t = tree(p,a,b,sum)|tree(n - p - 1,a + p + 1,b + p,sum); 23 if (t == 0) { 24 if (sum < mini) { 25 mini = sum; 26 min_child = b[n - 1]; 27 } 28 else if (sum == mini) { 29 min_child = min(min_child,b[n - 1]); 30 } 31 } 32 return 1; 33 } 34 35 int main () { 36 string str; 37 // freopen("1.in","r",stdin); 38 while (getline(cin,str)) { 39 istringstream sss(str); 40 int a[10010],b[10010]; 41 int pos = 0; 42 while (sss >> a[pos++]) {} 43 getline(cin,str); 44 istringstream ss(str); 45 pos = 0; 46 while(ss >> b[pos++]) {} 47 mini = INT_MAX; 48 min_child = INT_MAX; 49 tree(pos - 1,a,b,0); 50 cout << min_child << endl; 51 } 52 }
标签:des style blog http io ar color os sp
原文地址:http://www.cnblogs.com/xiaoshanshan/p/4122644.html