1143 Lowest Common Ancestor (30)

发布于:2025-07-06 ⋅ 阅读:(9) ⋅ 点赞:(0)

The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants.

A binary search tree (BST) is recursively defined as a binary tree which has the following properties:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • Both the left and right subtrees must also be binary search trees.

Given any two nodes in a BST, you are supposed to find their LCA.

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers: M (≤ 1,000), the number of pairs of nodes to be tested; and N (≤ 10,000), the number of keys in the BST, respectively. In the second line, N distinct integers are given as the preorder traversal sequence of the BST. Then M lines follow, each contains a pair of integer keys U and V. All the keys are in the range of int.

Output Specification:

For each given pair of U and V, print in a line LCA of U and V is A. if the LCA is found and A is the key. But if A is one of U and V, print X is an ancestor of Y. where X is A and Y is the other node. If U or V is not found in the BST, print in a line ERROR: U is not found. or ERROR: V is not found. or ERROR: U and V are not found..

Sample Input:

6 8
6 3 1 2 5 4 8 7
2 5
8 7
1 9
12 -3
0 8
99 99

Sample Output:

LCA of 2 and 5 is 3.
8 is an ancestor of 7.
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
ERROR: 0 is not found.
ERROR: 99 and 99 are not found.

题目大意:给出一棵二叉搜索树的前序遍历序列,查询给出值 u 和 v 的共同最低祖先的值。注意输出要求。
分析:先用一个 map 记录出现过的值,这样在读入查询的时候就能检查查询值是否在二叉搜索树中。这道题无需建树,不妨设 u 小于 v,且一定都存在于二叉搜索树中。u 和 v 的最近公共祖先要么是 u 或者 v 本身,要么是一个处于 u 和 v 中间的值。

查找最近公共祖先时,从序列的第一个值val 开始检查(也就是二叉搜索树的根节点),如果 val >= u 且 val <= v,说明就是要找的公共祖先,否则如果 val > u 且 val > v,说明 u 和 v 都在当前节点的右子树,则在前序序列中找到第一个大于 val 的值,继续查找;如果 val < u 且 val < v,说明 u 和 v 都在当前节点的左子树,则在前序序列中找到第一个小于 val 的值,继续查找。这样直到找到 u 或者 v 本身,或者是找到一个 val 处于 u 和 v 中间即为答案。

#include<algorithm>
#include <iostream>
#include  <cstdlib>
#include  <cstring>
#include   <string>
#include   <vector>
#include   <cstdio>
#include    <queue>
#include    <stack>
#include    <ctime>
#include    <cmath>
#include      <map>
#include      <set>
#define INF 0x3fffffff
#define db1(x) cout<<#x<<"="<<(x)<<endl
#define db2(x,y) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<endl
#define db3(x,y,z) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<endl
#define db4(x,y,z,r) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<", "<<#r<<"="<<(r)<<endl
#define db5(x,y,z,r,w) cout<<#x<<"="<<(x)<<", "<<#y<<"="<<(y)<<", "<<#z<<"="<<(z)<<", "<<#r<<"="<<(r)<<", "<<#w<<"="<<(w)<<endl
#define NUMBER_OF_THREADS   10
using namespace std;

int find_anc(int nums[],int n,int index,int a,int b)
{
    if(nums[index]>=a&&nums[index]<=b)return nums[index];

    if(nums[index]>a&&nums[index]>b)return find_anc(nums,n,index+1,a,b);
    else if(nums[index]<a&&nums[index]<b)
    {
        int ind=index+1;
        for(;ind<n;++ind)
        {
            if(nums[ind]>=a||nums[ind]>=b)return find_anc(nums,n,ind,a,b);
        }
    }
    return -1;
}

int main(void)
{
    #ifdef test
    freopen("in.txt","r",stdin);
//    freopen("out.txt","w",stdout);
    clock_t start=clock();
    #endif //test

    int m,n,times=1;scanf("%d%d",&m,&n);
    int nums[n+5]={0};
    map<int,int>mp;
    for(int i=0;i<n;++i)
    {
        scanf("%d",&nums[i]);
        if(!mp[nums[i]])mp[nums[i]]=times,times++;
    }

    for(int i=0;i<m;++i)
    {
        int a,b;scanf("%d%d",&a,&b);
        int f1=1,f2=1;
        if(!mp[a])f1=0;
        if(!mp[b])f2=0;
        if(f1==0&&f2)printf("ERROR: %d is not found.\n",a);
        else if(f1&&f2==0)printf("ERROR: %d is not found.\n",b);
        else if(f1==0&&f2==0)printf("ERROR: %d and %d are not found.\n",a,b);
        else
        {

            int ans=0;
            if(a>b)ans=find_anc(nums,n,0,b,a);
            else ans=find_anc(nums,n,0,a,b);
            if(ans!=a&&ans!=b)printf("LCA of %d and %d is %d.\n",a,b,ans);
            else 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);
            }
        }
    }


    #ifdef test
    clockid_t end=clock();
    double endtime=(double)(end-start)/CLOCKS_PER_SEC;
    printf("\n\n\n\n\n");
    cout<<"Total time:"<<endtime<<"s"<<endl;        //s为单位
    cout<<"Total time:"<<endtime*1000<<"ms"<<endl;    //ms为单位
    #endif //test
    return 0;
}