PAT甲1143 Lowest Common Ancestor (30)

#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;

int A[10010];
int N,M;
int B[10010],C[10010];

struct node
{
    int x;
    node* lchild;
    node* rchild;
};

node* newnode(int x)
{
    node* root=new node;
    root->x=x;
    root->lchild=NULL;
    root->rchild=NULL;
    return root;
}

node* create(int s,int e)
{
    if(s>e)return NULL;
    int i;
    for(i=s+1;i<=e;i++)
    {
        if(A[i]>=A[s])break;
    }
    node *root=newnode(A[s]);
    root->lchild=create(s+1,i-1);
    root->rchild=create(i,e);
    return root;
}

int Asearch(node* root,int x,int a[])
{
    int num=0;
    while(root!=NULL)
    {
        if(root->x==x)
        {
            a[num++]=x;
            break;
        }
        else if(root->x>x)
        {
            a[num++]=root->x;
            root=root->lchild;
        }
        else if(root->x<x)
        {
            a[num++]=root->x;
            root=root->rchild;
        }
    }
    if(root==NULL)num=-1;
    return num;
}

int main()
{
    scanf("%d%d",&M,&N);
    for(int i=0;i<N;i++)
    {
        scanf("%d",&A[i]);
    }
    node* root=create(0,N-1);
    for(int i=0;i<M;i++)
    {
        int num1=0,num2=0;
        int x,y;
        scanf("%d%d",&x,&y);
        num1=Asearch(root,x,B);
        num2=Asearch(root,y,C);
        if(num1==-1&&num2==-1)
        {
            printf("ERROR: %d and %d are not found.\n",x,y);
        }
        else if(num1==-1)
        {
            printf("ERROR: %d is not found.\n",x);
        }
        else if(num2==-1)
        {
            printf("ERROR: %d is not found.\n",y);
        }
        else
        {
            int index=0;
            while(B[index]==C[index]&&index<num1&&index<num2)
            {
                index++;
            }
            index--;
            if(B[index]==x)
            {
                printf("%d is an ancestor of %d.\n",x,y);
            }
            else if(B[index]==y)
            {
                printf("%d is an ancestor of %d.\n",y,x);
            }
            else
            {
                printf("LCA of %d and %d is %d.\n",x,y,B[index]);
            }
        }
    }
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yhy489275918/article/details/80484903