#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
#include <vector>
#include <stack>
using namespace std;
stack<int> s;
struct node
{
int data;
node* l;
node* r;
};
node* root;
void insertt(int x,node* &p)
{
if(p==NULL)
{
p=(node*)malloc(sizeof(node));
p->data=x;
p->l=NULL;
p->r=NULL;
}
else if(x>=p->data)
insertt(x,p->r);
else if(x<p->data)
insertt(x,p->l);
}
void tra(node* p)
{
if(p!=NULL)
{
printf("%d ",p->data);
tra(p->l);
tra(p->r);
}
}
node* p1;
node* p2;
int x;
node* se1(node* p)
{
if(p==NULL)
{
return NULL;
}
if(p->data==x)
{
s.push(p->data);
return p;
}
else if(x >= p->data)
{
s.push(p->data);
// cout<<p->data<<endl;
return se1(p->r);
}
else if(x < p->data)
{
s.push(p->data);
// cout<<p->data<<endl;
return se1(p->l);
}
}
int main()
{// freopen("in.txt","r",stdin);
int N,M;
cin>>N>>M;
for(int i=0;i<M;i++)
{
int t;
cin>>t;
insertt(t,root);
}
while(N--)
{
stack<int> s1,s2;
int t1,t2;
cin>>t1>>t2;
p1=NULL;
p2=NULL;
x=t1;
p1=se1(root);
s1=s;
while(!s.empty())
s.pop();
x=t2;
p2=se1(root);
s2=s;
while(!s.empty())
s.pop();
if(p1==NULL&&p2!=NULL)
printf("ERROR: %d is not found.\n",t1);
else if(p2==NULL&&p1!=NULL)
printf("ERROR: %d is not found.\n",t2);
else if(p1==NULL&&p2==NULL)
printf("ERROR: %d and %d are not found.\n",t1,t2);
else
{
while(s1.size()!=s2.size()|| (s1.size()==s2.size()&&s1.top()!=s2.top()))
{
if(s1.size()>s2.size())
s1.pop();
else if(s2.size()>s1.size())
s2.pop();
else
{
s1.pop();
s2.pop();
}
}
if(s1.top()==s2.top())
{
if(s1.top()!=t1&&s2.top()!=t2)
{
printf("LCA of %d and %d is %d.\n",t1,t2,s1.top());
}
else if(s1.top()!=t1)
{
printf("%d is an ancestor of %d.\n",t2,t1);
}
else
printf("%d is an ancestor of %d.\n",t1,t2);
}
}
}
//tra(root);
return 0;
}
1143. Lowest Common Ancestor (30)---一个点超时
最新推荐文章于 2020-04-02 20:41:14 发布