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 andAis the key. But ifAis one of U and V, printX is an ancestor of Y.whereXisAandYis 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 ...
随机推荐
- P - How many
Give you n ( n < 10000) necklaces ,the length of necklace will not large than 100,tell me How man ...
- [bzoj2802][Poi2012]Warehouse Store_贪心_堆
Warehouse Store bzoj-2802 Poi-2012 题目大意:一家商店的连续n天内,每一天会进货$a_i$个,有且只有一个客人回来买$b_i$个,问至多满足多少人. 注释:$1\le ...
- [转]十五天精通WCF——第十四天 一起聊聊FaultException
我们在玩web编程的时候,可能你会不经意的见到一些http500的错误,我想你应该不会陌生的,原因你应该也知道,服务器异常嘛, 这时候clr会把这个未处理的异常抛给iis并且包装成http500的错 ...
- JSP 获取Request 经常使用參数
<input type="hidden" id="a" value="<%=request.getScheme()%>" ...
- Struts 配置文件
web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="htt ...
- SqlServer 自动备份策略设置
企业管理器中的Tools,Database Maintenance Planner,可以设置数据库的定期自动备份计划.并通过启动Sql server Agent来自动运行备份计划.具体步骤如下: 1. ...
- POJ 2728(最优比率生成树+01规划)
Dese ...
- Java 错误:找不到或无法加载主类(源文件中含有包名 package)
1. 问题定位 编译(javac)和执行(java)java 程序时,出现这种类型的错误:找不到或无法加载主类: 首先排除是否是环境变量配置不当造成的问题,只要保证,命令行界面能够识别 javac/j ...
- 78.员工个人信息保镖页面 Extjs 页面
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8" ...
- python关于文件的操作
总是记不住API.昨晚写的时候用到了这些,但是没记住,于是就索性整理一下吧: python中对文件.文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块. 得到当前工作目录,即当前Pyth ...