PAT 1143 Lowest Common Ancestor——与网上大部分解都不同

题目

分析

基础理论:

前序的特点:根左右
而排序树 父结点的值一定在 任意左右子树值的中间

具体分析:

序号0 1 2 3 4 5 6 7
前序6 3 1 2 5 4 8 7
2 5

  1. 若能在给的点(最靠前的点)前面 找到一个值在 给的值中间
    那么一定是ACL
    即假如给的是5 2,则最靠前的是2 ,序号3 ;
    则在序号0——3中找一个值x 符合 2<x<5
    6 3 1 2 ——》根为 3

  2. 如果找不到呢?
    例如8 7
    则序号最前的是父结点
    比如给出的若是 7 8
    其中7序号为7,8序号为6
    则8序号小,为父结点

具体实现

  1. 用map保存序号
  2. 通过三目运算符来判断 哪个没找到/按照顺序传递x,y
  3. 注意输出“LCA of x and y is 3.”中按照题目给的x,y顺序进行输出,而不是排过序的;否则有测试点报错

代码

#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()) {//用一句话合并掉2次类似判定 // 避免特地写个函数 或是写3给if
			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]);//注意要按照题目给的xy顺序输出,而不是front->first, back->first
			return;
		}
	}
	printf("%d is an ancestor of %d.\n", front->first, back->first);
}

进阶例题:PAT 1151

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值