PAT 1143 Lowest Common Ancestor——不建树直接上

分析

本题需要理清楚一些基础概念:LCA、BST、前序遍历

本题的判断可分为2类:

能找到:

            8 is an ancestor of 7.
            LCA of 2 and 5 is 3.

找不到:

            ERROR: 9 is not found.
            ERROR: 12 and -3 are not found.

进一步分析:能找到

 LCA of 2 and 5 is 3.即意味 2和5前面存在一个数,介于2、5之间

(BST和前序的特点决定)

8 is an ancestor of 7.即意味不存在这个数

其他注意事项

LCA of 2 and 5 is 3. 应按照题目给出的顺序进行输出,即2、5;你不能5,2输出

 

代码

#include<bits/stdc++.h>
using namespace std;

int pairs{ 0 }, quantity{ 0 }, x, y;
map<int, int>id;
vector<int>bst;

void Judge(map<int, int>::iterator, map<int, int>::iterator);
int main() {
	scanf("%d %d", &pairs, &quantity);
	bst.resize(quantity);
	for (int i = 0; i < quantity; i++) {
		scanf("%d", &x);
		bst[i] = x;
		id[x] = i;
	}
	map<int, int>::iterator xid, yid;
	for (int i = 0; i < pairs; i++) {
		scanf("%d %d", &x, &y);
		xid = id.find(x);
		yid = id.find(y);
		if (xid == id.end() || yid == id.end()) {
			if (xid == id.end() && yid == id.end()) {
				printf("ERROR: %d and %d are not found.\n", x, y);
				continue;
			}
			printf("ERROR: %d is not found.\n", xid == id.end() ? x : y);
			continue;
		}
		xid->second > yid->second ? Judge(yid, xid) : Judge(xid, yid);
	}
	return 0;
}
void Judge(map<int, int>::iterator front, map<int, int>::iterator back) {
	for (int i = 0; i != front->second; i++) {
		if (bst[i] > front->first && bst[i] < back->first) {
			printf("LCA of %d and %d is %d.\n", x, y, bst[i]);
			return;
		}
	}
	printf("%d is an ancestor of %d.\n", front->first, back->first);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值