PAT甲级-1143 Lowest Common Ancestor (30 分)

题目:1143 Lowest Common Ancestor (30 分)
分析:第一次写的时候先建树,然后在树中向父母进行查找判断,很麻烦。看了题解之后发现可以利用二叉树的特性来解决。
#include<iostream>
#include<algorithm>
#include<math.h>
#include<cstring>
#include<queue>
#include<stack>
#include<map>
using namespace std;
int n,m,k;
int pre[10090];
map<int,int>visi;
int main(){
    
    
    cin>>m>>n;
    Node *root = NULL;
    for(int i = 0;i<n;i++)
    {
    
    
        cin>>pre[i];
        visi[pre[i]] = 1;   
    }
    while(m--)
    {
    
    
        int a,b;
        cin>>a>>b;
        if(visi[a] == 0 && visi[b] == 0)
            printf("ERROR: %d and %d are not found.\n",a,b);
        else if(visi[a] == 0)
            printf("ERROR: %d is not found.\n",a);
        else if(visi[b] == 0)
            printf("ERROR: %d is not found.\n",b);
        else{
    
    
            int t;
            for(int j = 0;j<n;j++)
            {
    
    
                t = pre[j];
                if((pre[j]>=a && pre[j]<=b) || (pre[j]>=b && pre[j]<=a))
                    break;
            }
            if(t == a)
                printf("%d is an ancestor of %d.\n",a,b);
            else if(t == b)
                printf("%d is an ancestor of %d.\n",b,a);
            else
                printf("LCA of %d and %d is %d.\n",a,b,t);
        }
    }
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43567222/article/details/114385404