//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 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
*/
UVA548Tree
最新推荐文章于 2019-10-24 21:23:29 发布