常规解法,建树
中序遍历=升序排序
以为数据水写了好多map没卡过去(大概单次nlognlogn) 换了别的方法查找lca
这样查找为log级别
#include <bits/stdc++.h>
using namespace std;
#define FORP(i,a,b) for(int i=(a);i<=(b);i++)
#define db(a) (cout<<"----"<<a<<endl)
int pre[100020];
int in[100020];
struct node{
int data;
struct node *left,*right;
};
map<int,int> mymap;
node * build(node *rt,int begin_pre,int begin_in,int begin_post,int n){
if(n==0) return NULL;
if(rt==NULL){
rt=new node();
rt->left=rt->right=NULL;
rt->data=pre[begin_pre];
}
int i=begin_in;
while(in[i]!=pre[begin_pre]) ++i;
int L=i-begin_in;
int R=n-L-1;
rt->left=build(rt->left,begin_pre+1,begin_in,begin_post,L);
rt->right=build(rt->right,begin_pre+1+L,begin_in+L+1,begin_post+L,R);
return rt;
}
int lca(node *rt,int a,int b){
if(a<rt->data&&b<rt->data) return lca(rt->left,a,b);
if(a>rt->data&&b>rt->data) return lca(rt->right,a,b);
return rt->data;
}
int main(){
int m,n;
scanf("%d%d",&n,&m);
FORP(i,1,m){
scanf("%d",pre+i);
mymap[pre[i]]++;
in[i]=pre[i];
}
sort(in+1,in+1+m);
struct node *rt=NULL;
rt=build(rt,1,1,1,m);
FORP(i,1,n){
int a,b;
scanf("%d%d",&a,&b);
map<int,int>::iterator It1=mymap.find(a);
map<int,int>::iterator It2=mymap.find(b);
if(It1==mymap.end()&&It2==mymap.end()){
printf("ERROR: %d and %d are not found.\n",a,b);
}
else if(It1==mymap.end()){
printf("ERROR: %d is not found.\n",a);
}
else if(It2==mymap.end()){
printf("ERROR: %d is not found.\n",b);
}
else{
int ans=lca(rt,a,b);
if(ans==a){
printf("%d is an ancestor of %d.\n",a,b );
}
else if(ans==b){
printf("%d is an ancestor of %d.\n",b,a );
}
else{
printf("LCA of %d and %d is %d.\n",a,b,ans );
}
}
}
return 0;
}
被人花式过。。。
#include <bits/stdc++.h>
using namespace std;
#define FORP(i,a,b) for(int i=(a);i<=(b);i++)
#define db(a) (cout<<"----"<<a<<endl)
int pre[100020];int m,n;
int lca(int a,int b){
FORP(i,1,m){
if((pre[i]>=a&&pre[i]<=b)||(pre[i]>=b&&pre[i]<=a)){
return pre[i];
}
}
return 0;
}
map<int,int>mymap;
int main(){
scanf("%d%d",&n,&m);
FORP(i,1,m){
scanf("%d",pre+i);
mymap[pre[i]]++;
}
FORP(i,1,n){
int a,b;
scanf("%d%d",&a,&b);
map<int,int>::iterator It1=mymap.find(a);
map<int,int>::iterator It2=mymap.find(b);
if(It1==mymap.end()&&It2==mymap.end()){
printf("ERROR: %d and %d are not found.\n",a,b);
}
else if(It1==mymap.end()){
printf("ERROR: %d is not found.\n",a);
}
else if(It2==mymap.end()){
printf("ERROR: %d is not found.\n",b);
}
else{
int ans=lca(a,b);
if(ans==a){
printf("%d is an ancestor of %d.\n",a,b );
}
else if(ans==b){
printf("%d is an ancestor of %d.\n",b,a );
}
else{
printf("LCA of %d and %d is %d.\n",a,b,ans );
}
}
}
return 0;
}