这道题目我认为只有这一种做法是nlogn的复杂度,,,,来记录一下,别的方法(一个一个插入的那种)对于深度很深的情况都是会把时间拖到n方的时间复杂度。这种做法建树过程中只有排序的时间最长;建树是n的时间复杂度(每一个节点遍历一次)。
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#define PII pair<double, int>
typedef long long ll;
using namespace std;
const int maxn = (1<<10)+100;
struct node
{
int data;
struct node *l,*r;
};
int pre[110000];
int ino[110000];
struct node *creat(int n,int *pre,int *ino)
{
// cout<<n<<endl;
if(n<1) return NULL;
struct node *it = new node;
it->data=pre[0];
it->l=it->r=NULL;
int i;
for(i=0;i<n;i++)
{
if(pre[0]==ino[i])
{
break;
}
}
it->l=creat(i,pre+1,ino);
it->r=creat(n-i-1,pre+i+1,ino+i+1);
return it;
}
map<int,bool> ma;
int zuihou=-1;
void find(struct node *it,int x,int y)
{
if(it==NULL)return ;
if(it->data>=x&&it->data<=y)
{
zuihou=it->data;
return ;
}
if(it->data>y)
find(it->l,x,y);
if(it->data<x)
find(it->r,x,y);
}
int main()
{
int n,m;
cin>>m>>n;
struct node *root;
root=NULL;
for(int i=0;i<n;i++)
{
cin>>pre[i];
ino[i]=pre[i];
ma[ino[i]]=true;
}
sort(ino,ino+n);
root=creat(n,pre,ino);
while(m--)
{
int x,y;
cin>>x>>y;
if(!ma[x]&&!ma[y])
{
printf("ERROR: %d and %d are not found.\n",x,y);
continue;
}
if(!ma[x])
{
printf("ERROR: %d is not found.\n",x);
continue;
}
if(!ma[y])
{
printf("ERROR: %d is not found.\n",y);
continue;
}
// cout<<root->r->data<<endl;
if(x<y)
find(root,x,y);
else find(root,y,x);
if(x==zuihou)
{
printf("%d is an ancestor of %d.\n",zuihou,y);
continue;
}
if(y==zuihou)
{
printf("%d is an ancestor of %d.\n",zuihou,x);
continue;
}
printf("LCA of %d and %d is %d.\n",x,y,zuihou);
}
return 0;
}