PAT 1151 LCA in a Binary Tree——与网上大部分解都不同

题目

目前看到最快的解法

(伪)建树中最快的解法

分析

基础理论:

前序的特点:根左右

中序的特点:左根右

结论:(有)祖先一定同时同时出现在

········前序的左点前·········

·····中序的左右点中间······

具体分析:

序号0 1 2 3 4 5 6 7

前序5 3 7 2 6 4 8 1

中序7 2 3 4 6 5 1 8

  1. 例:2 6
    前序祖先范围为 5 3 7 2
    中序祖先范围为 2 3 4 6
    其中同时出现的仅有3
  2. 例:2 1
    前序祖先范围为 5 3 7 2 6 4 8 1
    中序祖先范围为 2 3 4 6 5 1
    其中同时出现的有5 3
    同时出现时,仅需抓前序中第一个匹配的,即5
    注:以上成立是保证给的是2 1,即顺序
    ······实际给出的有可能是1 2,则需要调序

具体实现

  1. 注意题目先给的是中序
  2. 用map保存值和序号
  3. 由于需要2次调整顺序,用一个函数进行调序
  4. 在进行匹配时,取出前序的元素,用for
    而是否在中序中匹配,不可用for(会超时)——》用map进行搜索,判断搜出来值在 给定值中间
    5.当然还有就是按照题目给的x,y顺序输出“8 is an ancestor of 1.”

代码

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

int pairs{ 0 }, quantity{ 0 }, x, y;
vector<int>preorder, inorder;
map<int, int>pre_id, in_id;

void Judge(map<int, int>::iterator, map<int, int>::iterator, int, int);
void AdjustOrder(map<int, int>::iterator&, map<int, int>::iterator&);
int main() {
	scanf("%d %d", &pairs, &quantity);
	inorder.resize(quantity);
	for (int i = 0; i < quantity; i++) {
		scanf("%d", &x);
		inorder[i] = x;
		in_id[x] = i;
	}
	preorder.resize(quantity);
	for (int i = 0; i < quantity; i++) {
		scanf("%d", &x);
		preorder[i] = x;
		pre_id[x] = i;
	}
	for (int i = 0; i < pairs; i++) {
		scanf("%d %d", &x, &y);
		auto x_pre_id = pre_id.find(x);
		auto y_pre_id = pre_id.find(y);
		if (x_pre_id == pre_id.end() || y_pre_id == pre_id.end()) {
			if (x_pre_id == pre_id.end() && y_pre_id == pre_id.end()) {
				printf("ERROR: %d and %d are not found.\n",x,y);
				continue;
			}
			printf("ERROR: %d is not found.\n", x_pre_id == pre_id.end() ? x : y);
			continue;
		}
		auto x_in_id = in_id.find(x);
		auto y_in_id = in_id.find(y);
		AdjustOrder(x_in_id, y_in_id);
		AdjustOrder(x_pre_id, y_pre_id);
		Judge(x_pre_id, y_pre_id, x_in_id->second, y_in_id->second);
	}
	return 0;
}
void Judge(map<int, int>::iterator front, map<int, int>::iterator back,int in_front,int in_back) {
	if (in_front + 1 != in_back) {
		for (int i = 0; i < front->second; i++) {
			auto j = in_id.find(preorder[i]);
			if ( j->second <in_back && j->second>in_front) {
				printf("LCA of %d and %d is %d.\n", x, y, j->first);
				return;
			}
		}
	}
	printf("%d is an ancestor of %d.\n", front->first, back->first);
}
void AdjustOrder(map<int, int>::iterator& x, map<int, int>::iterator& y) {
	if (x->second > y->second) {
		swap(x, y);
	}
}

弱化例题:PAT 1143

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值