1143 Lowest Common Ancestor (30 分)

本文介绍了一个使用C++实现的算法,用于在给定的整数对(u, v)中查找是否存在一个整数x,使得x是u和v的最近公共祖先。程序通过读取输入的整数集合,然后对于每一对整数(u, v),检查是否存在一个x满足条件,并输出相应的结果。如果找到这样的x,将输出x与u或v的关系,或者它们的最近公共祖先。
#include <iostream>
#include <vector>
#include <map>
#include <cstdio>
using namespace std;
vector<int> p;
map<int, int> mp;
bool check(int x, int u, int v)
{
    if(x <= u && x >= v)
        return true;
    if(x >= u && x <= v)
        return true;
    if(x == u || x == v)
        return true;
    return false;
}
int main()
{
    int n, m, u, v, x;
    while(cin >> n >> m)
    {
        for(int i = 0; i < m; i++)
        {
            cin >> x;
            p.push_back(x);
            mp[x]++;
        }
        for(int i = 0; i < n; i++)
        {
            cin >> u >> v;
            for(int j = 0; j < m; j++)
            {
                x = p[j];
                if(check(x, u, v))
                    break;
            }
            if(mp[u] == mp[v] && mp[u] == 0)
            {
                printf("ERROR: %d and %d are not found.\n",u, v);

            }
            else if(mp[u] == 0)
            {
                printf("ERROR: %d is not found.\n", u);
            }
            else if(mp[v] == 0)
            {
                printf("ERROR: %d is not found.\n", v);
            }
            else
            {
                if(x == u)
                {
                    printf("%d is an ancestor of %d.\n", x, v);
                }
                else if(x == v)
                {
                    printf("%d is an ancestor of %d.\n", x, u);

                }
                else
                {
                    printf("LCA of %d and %d is %d.\n", u, v, x);
                }
            }
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值