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");
}
}