#include<iostream>
#include<cstring>
#include<unordered_map>
#include<algorithm>
using namespace std;
const int N=100010; //数组开到100000 pat就ac了神奇。
int m,n;
int in[N],pre[N];
unordered_map<int,int> pos;
int p[N],depth[N];
int build(int il,int ir,int pl,int pr,int d)
{
int root=pre[pl];
int k=pos[root];
depth[root]=d;
if(il<k) p[build(il,k-1,pl+1,pl+1+(k-1-il),d+1)]=root;
if(k<ir) p[build(k+1,ir,pl+1+(k-1-il)+1,pr,d+1)]=root;
return root;
}
int main()
{
cin>>m>>n;
for(int i=0;i<n;i++)
{
cin>>pre[i];
in[i]=pre[i];
}
sort(in,in+n);
for(int i=0;i<n;i++)
pos[in[i]]=i;
build(0,n-1,0,n-1,0);
while(m--)
{
int a,b;
cin>>a>>b;
if(pos.count(a)&&pos.count(b))
{
int x=a,y=b;
while(a!=b)
if(depth[a]<depth[b]) b=p[b];
else a=p[a];
if(a!=x&&b!=y) printf("LCA of %d and %d is %d.\n", x, y, a);
else if(a==x) printf("%d is an ancestor of %d.\n", x, y);
else printf("%d is an ancestor of %d.\n", y, x);
}
else if(pos.count(a)==0&&pos.count(b)==0)
printf("ERROR: %d and %d are not found.\n", a, b);
else if(pos.count(a)==0)
printf("ERROR: %d is not found.\n", a);
else
printf("ERROR: %d is not found.\n", b);
}
return 0;
}
这段代码提交过后会
segmentation fault
。###这是因为depth数组的下标用了负数。
这是要离散化的原因,因为节点的权值有可能有负数,在pat上数据可能不够强,所以你开大空间最后能过