1151 LCA in a Binary Tree (30分)

这个题建树=死亡,建树的时间+处理的时间 直接超时,哭都没地方哭。。。

应该利用原题目给出的序列进行稍加处理,利用找根的方法去挨个比较。
附本人代码(参考柳神):

#include<iostream>
#include<vector>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
int N, M;
vector<int>Vin, Vpost;
map<int, int>Ma;
void LCA(int begin, int end, int preroot, int a, int b) {
	if (begin<1 || end>N || end < begin)return;
	int root = Ma[Vpost[preroot]], ina = Ma[a], inb = Ma[b];
	if (ina < root&&inb < root)LCA(begin, root - 1, preroot + 1, a, b);
	else if (ina > root&&inb > root)LCA(root + 1, end, preroot + root - begin + 1, a, b);
	else if ((ina > root&&inb < root) || (ina<root&&inb>root))printf("LCA of %d and %d is %d.\n", a, b,Vin[root]);
	else if (ina == root)printf("%d is an ancestor of %d.\n", a, b);
	else if(inb==root)printf("%d is an ancestor of %d.\n", b, a);
}
int main() {
	int v1, v2;
	scanf("%d%d", &M, &N);
	Vin.resize(N+1);
	Vpost.resize(N+1);
	for (int i = 1; i <=N; i++) {
		scanf("%d", &Vin[i]);
		Ma[Vin[i]] = i;
	}
	for (int i = 1; i <=N; i++) {
		scanf("%d", &Vpost[i]);
	}
	for (int i = 0; i < M; i++) {
		scanf("%d%d", &v1, &v2);
		if (Ma[v1]==0 &&Ma[v2] == 0)printf("ERROR: %d and %d are not found.\n",v1,v2);
		else if (Ma[v1] == 0)printf("ERROR: %d is not found.\n", v1);
		else if (Ma[v2] == 0)printf("ERROR: %d is not found.\n", v2);
		else LCA(1, N , 1, v1, v2);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值