A1151 LCA in a Binary Tree (30)

map很容易超时,找到一个位置之后把它记录下来再进行比较。
本题思路,用pos表示各数在中序排列中的位置。如果一左一右,则当前根节点就是lca。

#include<cstdio>
#include<iostream>
#include<map>
using namespace std;
const int maxn=10010;
int in[maxn],pre[maxn];
map<int,int> pos;
void Lca(int inl,int inr,int prel,int prer,int a,int b)
{
	int nowroot=pos[pre[prel]],pa=pos[a],pb=pos[b];
	if((pa>nowroot&&pb<nowroot)||(pa<nowroot&&pb>nowroot))
	{
		printf("LCA of %d and %d is %d.",a,b,pre[prel]);
	}
	else if(pa==nowroot)
	{
		printf("%d is an ancestor of %d.",a,b);
	}
	else if(pb==nowroot)
	{
		printf("%d is an ancestor of %d.",b,a);
	}
	else if(pa<nowroot&&pb<nowroot)
	{
		Lca(inl,nowroot-1,prel+1,prel+nowroot-inl,a,b);
	}
	else if(pa>nowroot&&pb>nowroot)
	{
		Lca(nowroot+1,inr,prer-inr+nowroot+1,prer,a,b);
	}
}
int main()
{
	int m,n;
	cin>>m>>n;
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&in[i]);
		pos[in[i]]=i;
	}
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&pre[i]);
	}
	for(int i=0;i<m;i++)
	{
		int a,b;
		scanf("%d %d",&a,&b);
		int pa=pos[a],pb=pos[b];
		if(pa==0&&pb==0)
		{
			printf("ERROR: %d and %d are not found.",a,b);
		}
		else if(pa==0&&pb!=0)
		{
			printf("ERROR: %d is not found.",a);
		}
		else if(pb==0&&pa!=0)
		{
			printf("ERROR: %d is not found.",b);
		}
        else 
        {
        	Lca(1,n,1,n,a,b);
		}
		printf("\n");
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值