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 ...
随机推荐
- 从事分布式系统,计算,hadoop
作者:廖君链接:https://www.zhihu.com/question/19868791/answer/88873783来源:知乎 分布式系统(Distributed System)资料 < ...
- SQL Server 日志
http://www.cnblogs.com/CareySon/category/354290.html http://blog.csdn.net/tjvictor/article/details/5 ...
- DTrace Probes In MySQL 自定义探针
Inserting user-defined DTrace probes into MySQL source code is very useful to help user identify the ...
- ERROR: mount point </.alt.rootd3_EISMar14/opt/oracle/product/10.2> is already in use
在给solaris系统升级的时候,用lu方法遇到下面的错误. -bash-3.2# lumount rootd3_EISMar14 ERROR: mount point </.alt.rootd ...
- maven 的plugin 的使用
mvn [plugin-name]:[goal-name] mvn compiler:compile 这里写的十分详细: https://www.tutorialspoint.com/maven/ma ...
- POJ 3748:位操作
位操作 Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 8964 Accepted: 3581 Description 如 ...
- selenium清空默认文字
默认输入框 鼠标点击上去还有文案 直接用 clear不可以
- 使用同步适配器(sync adapter)数据传输
在android设备与webserver之间实现数据同步能显著提高你的应用的有用性.让你的应用更受用户的欢迎. 比方说.你的数据上传给webserver,这就有了一个有用的备份.当用户的设备离线工作时 ...
- KNN in c++
Pseudo Code of KNN We can implement a KNN model by following the below steps: Load the data Initiali ...
- thinkphp的session用法
Session方法用于Session 设置.获取.删除和管理操作. Session 用于Session 设置.获取.删除和管理操作 用法 session($name, $value='') 参数 na ...