17年冬季第四题 PAT甲级 1143 Lowest Common Ancestor(30分)

2020年9月PAT甲级满分必备刷题技巧 这份技巧帮你一网打尽所有的要点 阅读详情

题目来源:https://pintia.cn/problem-sets/994805342720868352/problems/994805343727501312

备考汇总贴:2020年3月PAT甲级满分必备刷题技巧

题目

The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants.

A binary search tree (BST) is recursively defined as a binary tree which has the following properties:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • Both the left and right subtrees must also be binary search trees.

Given any two nodes in a BST, you are supposed to find their LCA.

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers: M (≤ 1,000), the number of pairs of nodes to be tested; and N (≤ 10,000), the number of keys in the BST, respectively. In the second line, N distinct integers are given as the preorder traversal sequence of the BST. Then M lines follow, each contains a pair of integer keys U and V. All the keys are in the range of int.

Output Specification:

For each given pair of U and V, print in a line LCA of U and V is A. if the LCA is found and A is the key. But if A is one of U and V, print X is an ancestor of Y. where X is A and Y is the other node. If U or V is not found in the BST, print in a line ERROR: U is not found. or ERROR: V is not found. or ERROR: U and V are not found..

Sample Input:

6 8
6 3 1 2 5 4 8 7
2 5
8 7
1 9
12 -3
0 8
99 99

Sample Output:

LCA of 2 and 5 is 3.
8 is an ancestor of 7.
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
ERROR: 0 is not found.
ERROR: 99 and 99 are not found.

题目大意(以下内容主要转载自liuchuo,补充了讲解)

给出一棵二叉搜索树的前序遍历,问结点u和v的共同最低祖先是谁

题目分析

1.二叉搜索树的前序遍历有个特点:排在前面的某个节点一定是“在它后面且不大于它的节点”的父亲。所以,将当前结点标记为a,如果u和v分别在a的左、右,或者u、v其中一个就是当前a,说明找到了这个共同最低祖先a,退出当前循环

2.map<int, bool> mp用来标记树中所有出现过的结点,遍历一遍pre数组

满分代码

#include <iostream>
#include <vector>
#include <map>
using namespace std;
map<int, bool> mp;
int main() {
    int m, n, u, v, a;
    scanf("%d %d", &m, &n);
    vector<int> pre(n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &pre[i]);
        mp[pre[i]] = true;
    }
    for (int i = 0; i < m; i++) {
        scanf("%d %d", &u, &v);
        for(int j = 0; j < n; j++) {
            a = pre[j];
            if ((a >= u && a <= v) || (a >= v && a <= u)) break;
        } 
        if (mp[u] == false && mp[v] == false)
            printf("ERROR: %d and %d are not found.\n", u, v);
        else if (mp[u] == false || mp[v] == false)
            printf("ERROR: %d is not found.\n", mp[u] == false ? u : v);
        else if (a == u || a == v)
            printf("%d is an ancestor of %d.\n", a, a == u ? v : u);
        else
            printf("LCA of %d and %d is %d.\n", u, v, a);
    }
    return 0;
}

其他解法(转载自其他网友)

建树、递归查找节点看看符不符合lca的定义。

#include<iostream>
#include<unordered_map>
#include<algorithm>
#include<unordered_set>
#include<string>
using namespace std;
#define MAX 10005
int pre[MAX],in[MAX],N,M;

typedef struct node{
    int left,right;
}node;
unordered_map<int,node>arr;
void CreatBST(int preL,int inL,int inR)
{
    if(inL>inR)return ;
    int i=inL;
    while(pre[preL]!=in[i])++i;
    if(i-inL)arr[pre[preL]].left=pre[preL+1];
    else arr[pre[preL]].left=0;
    if(inR-i)arr[pre[preL]].right=pre[preL+i-inL+1];
    else arr[pre[preL]].right=0;
    CreatBST(preL+1,inL,i-1);
    CreatBST(preL+i-inL+1,i+1,inR);
}
void findLCA(int v,int a,int b)
{
    if(a==v)printf("%d is an ancestor of %d.\n",a,b);
    else if(b==v)printf("%d is an ancestor of %d.\n",b,a);
    else if(a<v&&b>v||a>v&&b<v)printf("LCA of %d and %d is %d.\n",a,b,v);
    else if(a<v&&b<v)findLCA(arr[v].left,a,b);
    else findLCA(arr[v].right,a,b);
}
int main()
{
    //freopen("test.txt","r",stdin);
    int i,u,v,root;
    scanf("%d %d",&M,&N);
    for(i=0;i<N;++i){
        scanf("%d",&pre[i]);
        if(i==0)root=pre[0];
        in[i]=pre[i];
    }
    sort(in,in+N);
    CreatBST(0,0,N-1);
    while(M--){
        scanf("%d %d",&u,&v);
        if(!arr.count(u)&&!arr.count(v))printf("ERROR: %d and %d are not found.\n",u,v);
        else if(!arr.count(u)||!arr.count(v))printf("ERROR: %d is not found.\n",arr.count(u)?v:u);
        else findLCA(root,u,v);
    }
    return 0;
}

 

2020年7月第4题 PAT甲级真题 Replacement Selection (30分) When the input is much too large to fit into memory, we have to do external sorting instead of internal sorting. One of the key steps in external sorting is to generate sets of sorted records (also called runs) with limited internal memory. The simplest me 阅读详情

相关推荐

2019年9月8日秋季PAT甲级题解-4 Dijkstra Sequence (30 分) 详细分析

Dijkstra's algorithm is one of the very famous greedy algorithms. It is used for solving the single source shortest path problem which gives the shortest paths from one particular source vertex to all...

qiiingc的解题记录 3884

PAT 1085 PAT单位排行(后2测试点段错误)

PAT 1085 PAT单位排行 后2测试点段错误 待解决 C++

thwwu的博客 431

PAT-2019年冬季考试-甲级-7-1 Good in C (20分)超详解,几招就满分通过

题目: When your interviewer asks you to write “Hello World” using C, can you do as the following figure shows? Input Specification: Each input file contains one test case. For each case, the first part...

qiiingc的解题记录 3640

PAT甲级1144 The Missing Number 段错误

很简单的一道题,但是最后两个测试案例很蛋疼,改了很久终于ac了 最后一个测试案例,显示段错误,初步诊断为数组范围太小,但是开的太大又接受不了,测试发现给的数据可能会很大,因此原判定条件应还有个上限,即<100000 倒数第二个测试点 n为100000,并且刚好是1~100000,因此最小缺失数为100001,最后for循环上界改一下就通过了 #include<iostream&g...

Artorias的博客 323

PAT甲级数据结构类技术总结

本篇文章专门汇总特别需要注意的数据结构,将说明每种数据结构的引入和具体用法。

qiiingc的解题记录 3092

2020年7月第2题 PAT甲级真题 The Judger (25分)

A game of numbers has the following rules: at the beginning, two distinct positive integers are given by the judge. Then each player in turn must give a number to the judge. The number must be the difference of two numbers that are previously given, and mu

qiiingc的解题记录 3012

PAT-甲级-1143 Lowest Common Ancestor (30 分)

1143Lowest Common Ancestor(30分) The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants. A binary search tree (BST) is recursively...

valcanoshan的博客 174

19年冬季第四题 PAT甲级 1167 Cartesian Tree (30分)超级详解不AC都难

这道题的题眼: 1.给出的是个min-heap 最小堆,即所有父节点不大于子节点的二叉树。如果找到了目前区间的最小值,那就是个父节点。 2.给出的顺序是inorder 中序,也就是LNR。是不是想到了递归和分而治之的老方法了? 3.输出的顺序是level-order 层序。如果不建树,就是开个大数组,按照下标放;如果建树,就得用BFS遍历树了。 这道题的陷阱: 没有说是哪种二叉树,如果是最极端的那...

qiiingc的解题记录 2626

PAT 甲级 1143 Lowest Common Ancestor (30 分)

题目 题目跳转 1143 Lowest Common Ancestor (30 分) 分析 看到这道题首先想到的是构建好一颗BST然后查找两个节点的路径从尾部进行遍历找到第一个相同节点就是公共的最小节点。但是有一个点始终是超时的过不去。后来找了资料换了种思路,寻找两个点范围内的点[u,v]范围内,就是最小公共节点。 code #include <iostream> #include <stdio.h> #include <map> using namespace std

code_garden 218

2019年9月8日秋季PAT甲级题解-2-1161-Merging Linked Lists (25 分) 双解法

Given two singly linked listsL​1​​=a​1​​→a​2​​→⋯→a​n−1​​→a​n​​andL​2​​=b​1​​→b​2​​→⋯→b​m−1​​→b​m​​. Ifn≥2m, you are supposed to reverse and merge the shorter one into the longer one to obtain a li...

qiiingc的解题记录 2353

2020年7月第3题 PAT甲级真题 Safari Park (25分)

A safari park(野生动物园)has K species of animals, and is divided into N regions. The managers hope to spread the animals to all the regions, but not the same animals in the two neighboring regions. Of course, they also realize that this is an NP complete probl

qiiingc的解题记录 2131

PAT甲级1143 Lowest Common Ancestor【BST】

题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805343727501312 题意: 给定一个二叉搜索树,以及他的前序遍历序列。 现在有m组询问,对于给定的两个关键字值u,v问他们的最近公共祖先是谁。 思路: 根本跟LCA都没关系好吗。m不是很大,每组询问都查找一次u和v就行了。 因为是BST所以根据前...

weixin_30457065的博客 128

19春第三题 PAT甲级 1158 Telefraud Detection (25分) 用这个方法最好

题目 Telefraud(电信诈骗) remains a common and persistent problem in our society. In some cases, unsuspecting victims lose their entire life savings. To stop this crime, you are supposed to write a program ...

qiiingc的解题记录 1920

PAT 甲级1143 Lowest Common Ancestor (30 分,一个测试点未过)

The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants. A binary search tree (BST) is recursively defined as a binary tree which has ...

qq_38846633的博客 561

嵌入式开发避坑指南:用DWT做延时函数,这几个细节不注意代码会跑飞

本文深入探讨了在Cortex-M嵌入式开发中使用DWT实现精确延时函数的关键技巧与常见陷阱。针对DWT_CYCCNT计数器应用中的内核兼容性、溢出处理、编译器优化等五大核心问题,提供了工业级稳健解决方案,帮助开发者避免代码跑飞风险,实现微秒级高精度延时控制。

weixin_42653691的博客 158

SAC安装与相关库文件(.so)的安装

摘要 SAC: Seismic Analysis Code 是用于地震信号处理的一套软件。 本文将介绍SAC的安装,以及安装时遇到的一些问题。主要是一些动态库(lib**.so)找不到的问题。 本文的环境 64位的 Ubuntu 16.04 64位的系统是安装出现问题的主要原因 1. SAC获取与安装 SAC 的安装,只需要解压,然后修改环境变量即可!!!不需要任何编译!!! 1.1. SAC 获取与解压 SAC软件获取地址:http://ds.iris.edu/ds/nodes/dmc/forms/s.

WangCY的博客 4334

PAT 甲级 1143 Lowest Common Ancestor

首先根据后序遍历构建BST,在构建BST时,每个节点的父节点也保存为该节点的信息。然后写函数实现BST的查找。 准备工作完成后,开始读取输入数据寻找LCA。对于每组数据,先查找它是否存于BST中。如果都存在,那么写一个getLCA函数找到它们的LCA。 首先我们用U表示这两个数中的较大一个,V表示这两个数中的较小一个。getLCA函数首先找到U在BST中的位置,因为V小于U,所以在U的左子树中...

qq_39115541的博客 226

【PDN仿真笔记9-使用Sigrity PowerDC进行IR Drop仿真的方法】

使用Sigrity PowerDC进行IR Drop进行仿真的方法

qq_42682826的博客 8001

PAT甲级1143 Lowest Common Ancestor BST+LCA

本想建树然后通过递归左右子树的形式去做,但是发现题中说明最多有一万个结点,写完以后果然超时.... 判别LCA的方法 判断当前的两个点的位置情况,如果一个在左子树,一个在右子树,那么根便是最小公共祖先; 如果都在左子树,递归左子树判断;如果都在右子树,递归右子树判断; 如果一个就是根,那么它便是最小公共祖先 解决超时方法: 由于题目告知是bst树,其实只需要比较结点值便可以确定左右子树的关系。但是递归时根结点的判断比较麻烦。主要有如下两种情况: 1.都在左子树,那么左子树的根下标就是当前的..

Artorias的博客 286

【OD统一考试(B卷)】比赛的冠亚季军,Python 解答

比赛的规则是 0 号和 1 号比赛,2 号和 3 号比赛,以此类推,每一轮,相邻的运动员进行比赛,获胜的进入下一轮,实力值大的获胜,实力值相等的情况,id 小的情况下获胜,轮空的直接进入下一轮。第一轮比赛,id 为 0 实力值为 2 的运动员和 id 为 1 实力值为 3 的运动员比赛, 1 号胜出进入下一轮争夺冠亚军,id 为 2 的运动员和 id 为 3 的运动员比赛,3 号胜出进入下一轮争夺冠亚军;2 号与 0 号,比赛进行季军的争夺,2 号实力值为 4,0 号实力值 2,故 2 号胜出,得季军。

梦想橡皮擦,专栏100例写作模式先行者,现象级专栏 《Python 爬虫 100 例》作者、《滚雪球学 Python 专栏》原创者 1万+

ChatTutor:让AI老师“会写会画”,打造可视化、互动式智能教育新范式

ChatTutor是一款突破性的开源AI教学助手,通过可视化电子白板实现"边讲边写"的沉浸式教学体验。该项目支持数学公式手写输入、动态函数绘图、自动生成思维导图等功能,采用多智能体架构实现专业协同。未来将扩展至编程、物理等STEM教育领域,适用于学生自学、教师备课和教育平台集成。作为MIT协议开源项目,ChatTutor通过赋予AI"教学肢体语言",推动教育从信息传递转向可视化互动建构,重新定义了AI助教的可能性。

这里汇聚了前沿的技术分享与实用的开发技巧,带你探索从创意到企业的技术创业之路。 423

18冬第二题 PAT甲级 1153 Decode Registration Card of PAT (25分) 鸡贼的题

题目 A registration card number of PAT consists of 4 parts: the 1st letter represents the test level, namely,Tfor the top level,Afor advance andBfor basic; the 2nd - 4th digits are the test sit...

qiiingc的解题记录 3万+

独家开源|RK3588 平台 YOLOv5 Android 源码级解析:NPU 量化、多线程与目标跟踪实战

本文将带你完成一个完整的AI视觉项目:在搭载RK3588芯片的Android开发板上运行实时目标检测与跟踪应用。实战目标:成功运行官方YOLOV5摄像头实时检测案例技术深度:深入理解RKNN开发框架和源码实现核心技能:掌握NPU推理、多线程并发、目标跟踪等关键技术。

m0_71589036的博客 193

19年秋季第一题 PAT甲级 1161 Forever (20 分) 有点儿意思

如果喜欢我的文章请点赞让我知道噢 题目 7-1Forever(20分) "Forever number" is a positive integerAwithKdigits, satisfying the following constrains: the sum of all the digits ofAism; the sum of all the digits ...

qiiingc的解题记录 1913

Seurat-SCTransform与harmony整合学习

源于R tips:Seurat之SCTransform方法原理 (qq.com)Seurat对象在经过SCTransform处理后会增加一个SCT的Assay,里面的scaled.data就是经过scale之后的pearson residual值,这个值是用于后续降维聚类分析使用的。

hx2024的博客 2330

SAP_SD模块_SAP 消息号VF501(科目确定期间出错)

摘要: SAP SD模块中执行VF02销售开票时出现“科目确定期间出错”(VF501)问题,主要原因是系统无法找到匹配的总账科目。解决方案包括:检查物料主数据和客户主数据中的科目分配组是否维护,核对发票中的对应字段,并通过VKOA事务代码分析科目确定逻辑。若定价过程中配置的科目代码(如Z01)未在VKOA中完整映射(如缺少H1+S5+Z01组合),则会导致内部价格无法关联总账科目。需在SPRO路径下完善科目代码分配配置,确保定价类型与科目代码匹配。本文提供了详细的排查步骤和配置方法,帮助解决开票过账错误。

我小时候很黑的博客 354
上一篇: 18年秋季第四题 PAT甲级 1151 LCA in a Binary Tree (30分)
下一篇: 【解决报错】java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
浒鱼鱼
博客等级 码龄11年 287粉丝 70原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值