1143 Lowest Common Ancestor (30 分)

该博客讲解了如何使用C++实现lowest common ancestor (LCA)算法,解决在给定树状结构中查找两个节点的最近公共祖先问题。通过map数据结构和迭代查找,作者展示了如何处理查询和错误处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1143 Lowest Common Ancestor (30 分)

#include <iostream>
#include <map>
using namespace std;
map<int,int> m;
int a[10100];
int main() {
	int n, M, x, y, t;
	cin >> M >> n;
	for(int i = 0; i < n; ++i){
		cin >> a[i];
		m[a[i]] = 1;
	}
	while(M--) {
		cin >> x >> y;
		for(int j = 0; j < n; ++j){
			t = a[j];
			if((t > x && t < y) || (t < x && t > y) || t == x || t == y)
				break;
		}
		if(m[x] == 0 && m[y] == 0)
			printf("ERROR: %d and %d are not found.\n", x, y);
		else if(m[x] == 0 || m[y] == 0)
			printf("ERROR: %d is not found.\n", m[x] == 0 ? x : y);
		else if(t != x && t != y)
			printf("LCA of %d and %d is %d.\n", x, y, t);
		else
			printf("%d is an ancestor of %d.\n", t, t == x ? y : x);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值