PAT——1143 Lowest Common Ancestor 甲级

1143 Lowest Common Ancestor

题目

https://pintia.cn/problem-sets/994805342720868352/problems/994805343727501312

题意

给出一棵树的前序序列,判断两个节点的最近公共祖先(LCA)

题目解析

通过map<int,int>判断节点是否在树中

遍历前序序列,判断当前根节点是否符合祖先节点的特点(左右一大一小,或者就是待测的两个节点之一),找到了退出循环输出即可

注意,因为这颗树是BST,才能符合这个搜索逻辑

AC代码

#include<bits/stdc++.h>
using namespace std;
int m,n,t,x,y,pre[10001];
map<int,int> vis;
int main()
{
	scanf("%d %d",&m,&n);
	for(int i=0;i<n;i++)
	{
		scanf("%d",&pre[i]);
		vis[pre[i]]=1;
	}
	while(m--)
	{
		scanf("%d %d",&x,&y);
		for(int i=0;i<n;i++)
		{
			t=pre[i];
			if( (t>x&&t<y) || (t<x&&t>y) || t==x || t==y ) break;
		}
		if(!vis[x]&&!vis[y]) 
			printf("ERROR: %d and %d are not found.\n",x,y);
		else if(!vis[x]||!vis[y])
			printf("ERROR: %d is not found.\n",!vis[x]?x:y);
		else if(t==x)
			printf("%d is an ancestor of %d.\n",x,y);
		else if(t==y)
			printf("%d is an ancestor of %d.\n",y,x);
		else
			printf("LCA of %d and %d is %d.\n",x,y,t);
	}
}

参考

PAT 1143. Lowest Common Ancestor (30) – 甲级(强烈推荐去看一看,思路真的特别好,柳神强啊!)

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值