PAT_A1143#Lowest Common Ancestor
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.
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 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 BST, print in a lineERROR: U is not found.
orERROR: V is not found.
orERROR: 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.
Keys:
- 二叉树的建立
- 二叉树的遍历
- 二叉查找树(Binary Search Tree)
Attention:
- 该代码测试点4有时候会超时,可以看出来测试数据是不同的,考试的时候如果遇到一个测试点卡住了,不妨多提交几次,实在不行再优化
- 技巧性方法:BST中u和v的公共祖先r一定是介于u和v之间的,根据这个思路,可以直接遍历先序序列求解
- 更新了优化算法
Code:
/*
Data: 2019-06-25 14:50:00
Problem: PAT_A1143#Lowest Common Ancestor
AC: 54:02 题目大意:
BST定义:L < root <= R;
给定BST中两个结点,找出其最近公共祖先
输入:
第一行给出,测试数M<=1e3,结点数N<=1e4
第二行,先序给出N个不同的结点
接下来M行,给出结点U和V 基本思路:
遍历结点U和V,并存储从root至U,V的路径
比较路径上的结点,即可找到最近公共祖先
*/
#include<cstdio>
#include<vector>
#include<map>
using namespace std;
const int M=1e4+;
map<int,int> mp;
vector<int> p1,p2;
int v1,v2,f1,f2,bst[M];
struct node
{
int data;
node *lchild, *rchild;
}; node *Create(int l, int r)
{
if(l > r)
return NULL;
node *root = new node;
root->data = bst[l];
int k;
for(k=l+; k<=r; k++)
if(bst[k] > bst[l])
break;
root->lchild = Create(l+,k-);
root->rchild = Create(k,r);
return root;
} void Search(node *root)
{
if(root == NULL)
return;
if(f1) p1.push_back(root->data);
if(f2) p2.push_back(root->data);
if(root->data==v1) f1=;
if(root->data==v2) f2=;
Search(root->lchild);
Search(root->rchild);
if(f1) p1.pop_back();
if(f2) p2.pop_back();
} int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("Test.txt", "r", stdin);
#endif // ONLINE_JUDGE int n,m;
scanf("%d%d", &m,&n);
for(int i=; i<n; i++)
{
scanf("%d", &bst[i]);
mp[bst[i]]=;
}
node *root = Create(,n-);
for(int i=; i<m; i++)
{
scanf("%d%d", &v1,&v2);
if(mp[v1]== && mp[v2]==)
printf("ERROR: %d and %d are not found.\n", v1,v2);
else if(mp[v1]==)
printf("ERROR: %d is not found.\n", v1);
else if(mp[v2]==)
printf("ERROR: %d is not found.\n", v2);
else
{
p1.clear();f1=;
p2.clear();f2=;
Search(root);
while(p1.size() < p2.size())
p2.pop_back();
while(p1.size() > p2.size())
p1.pop_back();
int pos=p1.size()-;
while(p1[pos] != p2[pos])
pos--;
if(p1[pos] != v1 && p1[pos] != v2)
printf("LCA of %d and %d is %d.\n", v1,v2,p1[pos]);
else if(p1[pos] == v1)
printf("%d is an ancestor of %d.\n", v1,v2);
else
printf("%d is an ancestor of %d.\n", v2,v1);
}
} return ;
}
优化算法
#include<cstdio>
#include<map>
#include<algorithm>
using namespace std;
const int M=1e4+;
int pre[M],v1,v2;
map<int,int> mp; void Travel(int root)
{
if((pre[root]<v1&&pre[root]>v2)||(pre[root]>v1&&pre[root]<v2))
printf("LCA of %d and %d is %d.\n", v1,v2,pre[root]);
else if(pre[root]==v1)
printf("%d is an ancestor of %d.\n",v1,v2);
else if(pre[root]==v2)
printf("%d is an ancestor of %d.\n",v2,v1);
else
Travel(root+);
} int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("Test.txt", "r", stdin);
#endif // ONLINE_JUDGE int n,m;
scanf("%d%d", &m,&n);
for(int i=; i<=n; i++)
{
scanf("%d", &pre[i]);
mp[pre[i]]=;
}
while(m--)
{
scanf("%d%d", &v1,&v2);
if(mp[v1]== && mp[v2]==)
printf("ERROR: %d and %d are not found.\n",v1,v2);
else if(mp[v1]==)
printf("ERROR: %d is not found.\n", v1);
else if(mp[v2]==)
printf("ERROR: %d is not found.\n", v2);
else
Travel();
} return ;
}
PAT_A1143#Lowest Common Ancestor的更多相关文章
- [LeetCode] Lowest Common Ancestor of a Binary Tree 二叉树的最小共同父节点
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...
- [LeetCode] Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
- 48. 二叉树两结点的最低共同父结点(3种变种情况)[Get lowest common ancestor of binary tree]
[题目] 输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点. 二叉树的结点定义如下: C++ Code 123456 struct BinaryTreeNode { int ...
- [LeetCode]Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
- 数据结构与算法(1)支线任务4——Lowest Common Ancestor of a Binary Tree
题目如下:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ Given a binary tree, fin ...
- Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
- Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...
- leetcode 235. Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
- leetcode 236. Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...
随机推荐
- 浏览器最小字体小于12px解决方案
<style> p{font-size:10px;-webkit-transform:scale(0.8);} /*这里的数字0.8,是缩放比例,可以根据情况变化.*/ </styl ...
- 深入理解Java和MySQL乱码问题
近期我们使用tomcat和MySQL搭建了一个Java Webserver,并将游戏的server逻辑部署在该server上. 游戏上线后不久,我们发现数据库中出现了大量的乱码.这是个很严重的问题,因 ...
- 安装Office Web Apps Server 2013 – KB2592525安装失败
在Windows Server 2008 R2上安装 office web apps Server 的其中一个先决条件是 安装KB2592525. 但由于服务器已经打了SP1及其它大部分的patch, ...
- 经典左右布局demo
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8&qu ...
- NDK编译库执行时报dlopen failed: cannot locate symbol "__exidx_end" 解决的方法
当用NDK编译的库在执行载入时报例如以下错: dlopen("/data/data/xxx.xxx.xxx/lib/libxxx.so") failed: dlopen faile ...
- 升级到VS2013常见问题
问题1: Building an MFC project for a non-Unicode character set is deprecated 解决方法: 用于多字节字符编码 (MBCS) 的 ...
- 卡尔曼滤波(Kalman Filter) 的进一步讨论
我们在上一篇文章中通过一个简单的样例算是入门卡尔曼滤波了.本文将以此为基础讨论一些技术细节. 卡尔曼滤波(Kalman Filter) http://blog.csdn.net/baimafujinj ...
- Oracle数据库版本号定期检视与升级的必要性分析
目 录 ▇1.ORACLE数据库版本号知识 ▇2.看看自己的数据库还有没有支持服务 ▇3.看11.2.0.3版本号各PSU的公布时间与解决BUG数量列表 ▇4.看11.2.0.4版本号各PSU的公布时 ...
- Detach a Database
https://msdn.microsoft.com/en-us/library/ms191491.aspx 方法一:Using SQL Server Management Studio To det ...
- hdu1150——最小点覆盖
As we all know, machine scheduling is a very classical problem in computer science and has been stud ...