UVA548Tree

//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

*/

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值