Source:

PAT A1151 LCA in a Binary Tree (30 分)

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 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 binary tree, 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
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的更多相关文章

  1. 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 ...

  2. PAT-1151(LCA in a Binary Tree)+最近公共祖先+二叉树的中序遍历和前序遍历

    LCA in a Binary Tree PAT-1151 本题的困难在于如何在中序遍历和前序遍历已知的情况下找出两个结点的最近公共祖先. 可以利用据中序遍历和前序遍历构建树的思路,判断两个结点在根节 ...

  3. LCA of a Binary Tree

    236. Lowest Common Ancestor of a Binary Tree /** * 基础版 * 给定p,q都是在树中 * 有两种情况: * 1. p和q分布在LCA的两侧 * 2. ...

  4. 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 ...

  5. 【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 ...

  6. PAT 甲级 1151 LCA in a Binary Tree

    https://pintia.cn/problem-sets/994805342720868352/problems/1038430130011897856 The lowest common anc ...

  7. 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 ...

  8. 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 ...

  9. 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 ...

随机推荐

  1. web项目log日志查看分析->流程理解

    1.DEBUG [2017-07-10 11:38:41,705][] org.springframework.web.servlet.DispatcherServlet:865 - Dispatch ...

  2. Clojure:解决selmer模板不刷新的问题

    当在REPL环境中尝试调试template的时候,会发现每次都需要重启REPL才能看到最新的变化.调查后发现,原来是每次启动REPL的时候,原来的template文件都被放到了target目录中,这样 ...

  3. [Fri 26 Jun 2015 ~ Thu 2 Jul 2015] Deep Learning in arxiv

    Natural Neural Networks Google DeepMind又一神作 Projected Natural Gradient Descent algorithm (PRONG) bet ...

  4. BAPC2014 B&amp;&amp;HUNNU11582:Button Bashing(BFS)

    题意: 给出n,m,代表微波炉有n个button,要求达到总时间为m 然后给出n个数.代表n个button能添加的时间,问最少几步,可以使得按出的总时间大于等于要求的时间,而且相差最小 输出最小的步数 ...

  5. HDU 5538/ 2015长春区域 L.House Building 水题

    题意:求给出图的表面积,不包括底面 #include<bits/stdc++.h> using namespace std ; typedef long long ll; #define ...

  6. TF101出现“DMClient已停止”处理办法

    设定->应用程式->全部->DMClient强制停止 然后 清除数据 然后 重开机 测试通过.

  7. fsockopen get,post 封装 (转)

    function http_request($url, $method = 'GET', $postfields = NULL, $headers = array()) {   $parse = pa ...

  8. (Go)10.流程控制示例

    package main import ( "math/rand" "fmt" ) func main() { //var n int n := rand.In ...

  9. 什么是 less? 如何使用 less?

    什么是 Less? Less 是一门 CSS 预处理语言,它扩充了 CSS 语言,增加了诸如变量.混合(mixin).嵌套.函数等功能,让 CSS 更易编写.维护等. 本质上,Less 包含一套自定义 ...

  10. LocalDateTime查找最近的五分钟点

    /** * 最近的五分钟 * @param dateTime * @return */ public static LocalDateTime getNear5(LocalDateTime dateT ...