PAT_A1151#LCA in a Binary Tree
Source:
Description:
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.
Given any two nodes in a binary tree, 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 binary tree, respectively. In each of the following two lines, N distinct integers are given as the inorder and preorder traversal sequences of the binary tree, respectively. It is guaranteed that the binary tree can be uniquely determined by the input sequences. 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 andA
is the key. But ifA
is one of U and V, printX is an ancestor of Y.
whereX
isA
andY
is the other node. If U or V is not found in the binary tree, print in a lineERROR: U is not found.
orERROR: V is not found.
orERROR: U and V are not found.
.
Sample Input:
6 8
7 2 3 4 6 5 1 8
5 3 7 2 6 4 8 1
2 6
8 1
7 9
12 -3
0 8
99 99
Sample Output:
LCA of 2 and 6 is 3.
8 is an ancestor of 1.
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
ERROR: 0 is not found.
ERROR: 99 and 99 are not found.
Keys:
Attention:
- 没有卡时间,所以常规操作就能通过,基本功要扎实;
- 更新了优化算法;
Code:
基本方法:
/*
Data: 2019-05-13 21:06:50
Problem: PAT_A1151#LCA in a Binary Tree
AC: 57:30 题目大意:
求U和V最近公共祖先
输入:
第一行给出,M测试组数<=1e3,N结点数<=1e4
接下来两行给出,中序遍历和先序遍历
接下来M行给出,给出查询结点U和V
输出:
如果U和V有公共祖先,LCA of U and V is A. 其中,A是key值
如果U是V的祖先,A is an ancestor of V. 其中,A是key值,V是结点序号
如果U或V未找到,ERROR: U is not found.
如果U和V均未找到,ERROR: U and V are not found.
*/ #include<cstdio>
#include<stack>
#include<map>
using namespace std;
const int M=1e4+;
int in[M],pre[M],v1,v2,f1,f2;
stack<int> p1,p2;
map<int,int> key;
struct node
{
int data;
node *lchild,*rchild;
}; node* Create(int preL,int preR,int inL,int inR)
{
if(preL > preR)
return NULL;
node *root = new node;
root->data = pre[preL];
int k;
for(k=inL; k<=inR; k++)
if(in[k]==root->data)
break;
int numLeft = k-inL;
root->lchild = Create(preL+,preL+numLeft,inL,k-);
root->rchild = Create(preL+numLeft+,preR,k+,inR);
return root;
} void DFS(node *root)
{
if(!root)
return;
if(f1) p1.push(root->data);
if(f2) p2.push(root->data);
if(root->data==v1) f1=;
if(root->data==v2) f2=;
DFS(root->lchild);
DFS(root->rchild);
if(f1) p1.pop();
if(f2) p2.pop();
} int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("Test.txt", "r", stdin);
#endif int n,m;
scanf("%d%d", &m,&n);
for(int i=; i<n; i++)
scanf("%d", &in[i]);
for(int i=; i<n; i++)
{
scanf("%d", &pre[i]);
key[pre[i]]=;
}
node *root = Create(,n-,,n-);
for(int i=; i<m; i++)
{
scanf("%d%d",&v1,&v2);
if(key[v1]== && key[v2]==)
printf("ERROR: %d and %d are not found.\n", v1,v2);
else if(key[v1]== || key[v2]==)
printf("ERROR: %d is not found.\n", key[v2]==?v2:v1);
else
{
while(!p1.empty()) p1.pop();
while(!p2.empty()) p2.pop();
f1=;f2=;
DFS(root);
while(p1.size() > p2.size()) p1.pop();
while(p2.size() > p1.size()) p2.pop();
while(p1.top() != p2.top())
{p1.pop();p2.pop();}
if(p1.top()!=v1 && p1.top()!=v2)
printf("LCA of %d and %d is %d.\n",v1,v2,p1.top());
else if(p1.top() == v1)
printf("%d is an ancestor of %d.\n", v1,v2);
else
printf("%d is an ancestor of %d.\n", v2,v1);
}
} return ;
}
优化算法:
/*
Data: 2019-06-29 15:55:25
Problem: PAT_A1151#LCA in a Binary Tree
AC: 38:24 题目大意:
求U和V最近公共祖先
输入:
第一行给出,M测试组数<=1e3,N结点数<=1e4
接下来两行给出,中序遍历和先序遍历
接下来M行给出,给出查询结点U和V
输出:
如果U和V有公共祖先,LCA of U and V is A. 其中,A是key值
如果U是V的祖先,A is an ancestor of V. 其中,A是key值,V是结点序号
如果U或V未找到,ERROR: U is not found.
如果U和V均未找到,ERROR: U and V are not found. 基本思路:
若U和V存在,根据先序序列依次遍历根结点,设为root
中序遍历中,若U和V分别在root的两端,则说明该结点为公共祖先(显然)
且该结点一定是最近公共祖先(存在且唯一)
证明:
若roo1是U和V的最近公共祖先,存在root2是U和V的非最近公共祖先
则root1位于root2的左子树或右子树(或者说roo1位于root2至U和V的路径上),
而U和V是root1的子树
故U和V位于root2的左子树或右子树
故有且仅有最近公共祖先,位于U和V的中间
*/
#include<cstdio>
#include<unordered_map>
using namespace std;
const int M=1e4+;
int in[M],pr[M];
unordered_map<int,int> pin,ppr;
int n,m,v1,v2; void LCA(int prL, int prR, int inL, int inR)
{
if(prL > prR)
return;
int rt=pr[prL];
int numLeft=pin[rt]-inL;
if(rt == v1)
{
printf("%d is an ancestor of %d.\n", rt,v2);
return;
}
else if(rt == v2)
{
printf("%d is an ancestor of %d.\n", rt,v1);
return;
}
else if(pin[v1]<pin[rt] && pin[v2]<pin[rt])
LCA(prL+,prL+numLeft,inL,pin[rt]-);
else if(pin[v1]>pin[rt] && pin[v2]>pin[rt])
LCA(prL+numLeft+,prR,pin[rt]+,inR);
else
printf("LCA of %d and %d is %d.\n", v1,v2,rt);
} int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("Test.txt", "r", stdin);
#endif // ONLINE_JUDGE scanf("%d%d", &m,&n);
for(int i=; i<=n; i++)
{
scanf("%d", &in[i]);
pin[in[i]]=i; }
for(int i=; i<=n; i++)
{
scanf("%d", &pr[i]);
ppr[pr[i]]=i;
}
while(m--)
{
scanf("%d%d", &v1,&v2);
if(pin[v1]== && pin[v2]==)
printf("ERROR: %d and %d are not found.\n", v1,v2);
else if(pin[v1]==)
printf("ERROR: %d is not found.\n", v1);
else if(pin[v2]==)
printf("ERROR: %d is not found.\n", v2);
else
LCA(,n,,n);
} return ;
}
PAT_A1151#LCA in a Binary Tree的更多相关文章
- PAT 1151 LCA in a Binary Tree[难][二叉树]
1151 LCA in a Binary Tree (30 分) The lowest common ancestor (LCA) of two nodes U and V in a tree is ...
- PAT-1151(LCA in a Binary Tree)+最近公共祖先+二叉树的中序遍历和前序遍历
LCA in a Binary Tree PAT-1151 本题的困难在于如何在中序遍历和前序遍历已知的情况下找出两个结点的最近公共祖先. 可以利用据中序遍历和前序遍历构建树的思路,判断两个结点在根节 ...
- LCA of a Binary Tree
236. Lowest Common Ancestor of a Binary Tree /** * 基础版 * 给定p,q都是在树中 * 有两种情况: * 1. p和q分布在LCA的两侧 * 2. ...
- PAT A1151 LCA in a Binary Tree (30 分)——二叉树,最小公共祖先(lca)
The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U ...
- 【PAT 甲级】1151 LCA in a Binary Tree (30 分)
题目描述 The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has bo ...
- PAT 甲级 1151 LCA in a Binary Tree
https://pintia.cn/problem-sets/994805342720868352/problems/1038430130011897856 The lowest common anc ...
- 1151 LCA in a Binary Tree(30 分)
The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U ...
- PAT Advanced 1151 LCA in a Binary Tree (30) [树的遍历,LCA算法]
题目 The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both ...
- 1151 LCA in a Binary Tree
The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U ...
随机推荐
- Linux排查java程序占用cpu过高的线程代码
分几步骤: 1.通过top,查出占用CPU过高的java进程 ,比如: pid :6666 2.通过ps -mp 6666 -o THREAD,tid,time| sort -n -k1 -r 查看此 ...
- IntelliJ IDEA 在左右两侧出现Project、Maven Project等导航按钮
IntelliJ IDEA 在左右两侧出现Project.Maven Project等导航按钮 选中 View > Tool Buttons 可以查看Project.Maven Project等 ...
- spring主要产品
Spring Framework * Spring Web Flow * Spring Web Services * Spring Security (Acegi Security) ...
- update_notifier 造成nodejs进程数量增长的问题
最近运维老大j哥找到我说了一个事儿:某私有化部署的线上环境nodejs进程数量多达1000+,对比公版线上环境的66个进程数显得十分诡异.并且单个nodejs进程所占用swap空间也较大,也不释放空间 ...
- jenkins设置
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PAT ...
- 【Linux】Ubuntu 开机默认亮度改动方法
换了ubuntu 之后.发现开机屏幕都是"最大亮度",每次都要到设置中手动调节,非常麻烦.于是想到去改动这个设置.Google一通,别人可行的办法到我这就没用了.郁闷.最后是在st ...
- HDU5489 LIS变形
Removed Interval Problem Description Given a sequence of numbers A=a1,a2,…,aN , a subsequence b1,b2, ...
- android.os.Process.killProcess(android.os.Process.myPid())与Activity生命周期的影响
如果通过finish方法结束了一个Activity,那么根据Activity的生命周期,则会自动调用Activity的销毁方法onDestory(),但是在项目中遇到这样的一个问题,就是Activi ...
- Getting Installation aborted (Status 7) ApplyParsePerms: lsetfilecon of /syst...【转】
OTA升级失败:原文http://en.miui.com/thread-112197-1-1.html Do you get this "Status 7" error in Re ...
- Framebuffer子系统【转】
本文转载自:http://blog.csdn.net/av_geek/article/details/40897115 本文将介绍Framebuffer子系统 目标平台:TQ2440 CPU:s3c2 ...