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 ...
随机推荐
- cogs 1310. [HAOI2006]聪明的猴子
1310. [HAOI2006]聪明的猴子 ★ 输入文件:monkey.in 输出文件:monkey.out 简单对比时间限制:1 s 内存限制:128 MB [题目描述] 在一个热带 ...
- mapreduce v1.0学习笔记
它是什么? 一个用于处理大数据开源的分布式计算框架,它由java实现,原生提供java编程交互接口,其它语言通过hadoop streaming方式和mapreduce框架交互. 可以做什么? 利用框 ...
- HDU 4891 The Great Pan (字符串处理)
题目链接:HDU 4891 The Great Pan 求一串字符有多少种不同的意思,当中关心'{','}'之间的'|'. 和'$','$'之间的空格,连续N个空格算N+1种. AC代码: #incl ...
- Eclipse ADT 导入别的电脑开发的项目
用Eclipse开发的时候常常要导入别的电脑开发的项目,常常会出错,甚至导入不了. 方法一: 把你正在使用的Eclipse开发的随便一个项目.打开,把下图这三个文件复制过去你要导入的项目.覆盖.然后再 ...
- 2014年辛星jquery解读第三节 Ajax
***************Ajax********************* 1.Ajax是Asynchronous Javascript And XML的简写,它指的是异步Javascript ...
- 【JavaScript】离开页面前提示
离开页面前的提示不能够用onunload去做,由于它仅仅是兼容IE,你要兼容Google与FireFox就蛋疼了. 并且这个事件还是关闭之后才会触发的. 取而代之能够用onbeforeunload去实 ...
- AAC帧格式及编码介绍
参考资料: AAC以adts格式封装的分析:http://wenku.baidu.com/view/45c755fd910ef12d2af9e74c.html aac编码介绍:http://wenku ...
- SQL Server2012 T-SQL基础教程--读书笔记(8 - 10章)
SQL Server2012 T-SQL基础教程--读书笔记(8 - 10章) 示例数据库:点我 CHAPTER 08 数据修改 8.1 插入数据 8.1.1 INSERT VALUES 语句 8.1 ...
- 截取字符(substr)检索字符位置(instr)
1.SUBSTR(string,start_position,[length]) 求子字符串,返回字符串注释: string 元字符串start_position 开始位置(从0开始)length 可 ...
- SnackDown Online Qualifier 2017
好久没做题了,然后就想着随便做一个.无奈cf都是晚上,然后就看见这个,随便做做. 资格赛,只要做出来1题就行了,4天的时间. 1. 水题 #include <iostream> #incl ...