UVA548Tree

来源:互联网 发布:淘宝商家版登录 编辑:程序博客网 时间:2024/05/13 06:34
//UVA548Tree#include<cstdio>#include<string>#include<iostream>#include<sstream>#include<cstring>using namespace std;typedef int* Node; const int MAXN = 10000 + 10;int in[MAXN], po[MAXN], tr[MAXN], tl[MAXN];int n = 0;bool read_in(Node a) {string s;if(!(getline(cin, s))) return false;stringstream ss(s);int tmp = 0; n = 0;while(ss >> tmp) a[n++] = tmp;return true;}int build(int in1, int in2, int po1, int po2) {if(in1 > in2) return 0;int root = po[po2];     int p = in1;while(root != in[p]) p++;int cnt = p - in1;//printf("p = %d, root = %d, in1 = %d, p - 1 = %d, pol = %d, pol + cnt - 1 = %d\n", p, root, in1, p - 1, po1, po1 + cnt - 1);tl[root] = build(in1, p - 1, po1, po1 + cnt - 1);tr[root] = build(p + 1, in2, po1 + cnt, po2 - 1);return root;}int MIN = 1e9;int tap = 1e5;void cal(int x, int sum) {sum += x;//printf("x = %d, tr[x] = %d, tl[x] = %d\n", x, tr[x], tl[x]);if(!tr[x] && !tl[x]) {//printf("sum = %d\n", sum);if(sum < MIN || (sum == MIN && x < tap)) {MIN = sum; tap = x;//printf("tap = %d\n", tap);}}else {if(tr[x]) cal(tr[x], sum);if(tl[x]) cal(tl[x], sum);}}int main() {while(read_in(in)) {MIN = 1e9;read_in(po);build(0, n - 1, 0, n - 1);int sum = 0;cal(po[n - 1], sum);    printf("%d\n", tap);memset(tr, 0, sizeof(tr));memset(tl, 0, sizeof(tl));memset(in, 0, sizeof(in));memset(po, 0, sizeof(po));}return 0;} /* 3 2 1 4 5 7 63 1 2 5 6 7 47 8 11 3 5 16 12 188 3 11 7 16 18 12 5255255*/