Source:

PAT A1143 Lowest Common Ancestor (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.

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 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 BST, 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
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:

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

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

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

  3. 48. 二叉树两结点的最低共同父结点(3种变种情况)[Get lowest common ancestor of binary tree]

    [题目] 输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点. 二叉树的结点定义如下:  C++ Code  123456   struct BinaryTreeNode {     int ...

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

  5. 数据结构与算法(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 ...

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

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

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

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

随机推荐

  1. discuz新的单点论坛(不依赖UCenter)

    discuz 本身提供UCENTER用户中心能够实现单点登录. 可是其它应用要单点登录到discuz还是存在若干问题: 须要2次激活.可能造成server无响应,论坛显示的最新注冊用户无法同步更新,官 ...

  2. Raphaeljs入门到精通(二)

    这节我们将介绍Raphaeljs中元素的属性和事件,案例还是以上一篇的代码展开 <!DOCTYPE html> <html xmlns="http://www.w3.org ...

  3. linux下jdk的安装和配置

    一.首先依据自己的系统位数在网上下载对应的jdk安装包 下载地址例如以下:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-do ...

  4. php debug二三事

    最近php相关项目遇到了一些问题,处理起来让人感觉挺有意思,寥寥记下. 1.php执行后常驻内存里,需要kill掉该进程再重启,才能让修改后的代码生效. 之前有一次组里小伙伴修改了一个长期后台进程运行 ...

  5. 开发DataSnapserver

     在上次的文章中讨论了怎样把传统的Delphi 主从架构应用程序逐渐转换为DataSnap JSONserver.在本篇文章中让我们正式讨论怎样使用Delphi XE开发DataSnap/REST ...

  6. jsonArray和Java List对象互转,日期处理

    List转jsonArray : // 格式化日期 JsonConfig jsonConfig = new JsonConfig(); DSHJsonDateValueProcessor dshJso ...

  7. expect安装测试-自动登陆脚本

    安装: yum list | grep expect yum install expect 参考:http://www.cnblogs.com/iloveyoucc/archive/2012/05/1 ...

  8. Android+Jquery Mobile学习系列(3)-创建Android项目

    前两章分别对开发环境和Jquery Mobile基础知识进行了介绍,本章介绍创建一个Android项目,并使用WebView控件显示HTML数据. 首先创建一个Android Application项 ...

  9. nyoj--1100--WAJUEJI which home strong!(bfs)

    WAJUEJI which home strong! 时间限制:1000 ms  |  内存限制:65535 KB 难度:2 描述 在一个山沟里,姐弟俩同时考上了大学.但由于家里拮据,所以这并不是什么 ...

  10. bzoj 1050 [ HAOI 2006 ] 旅行comf —— 并查集

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1050 没思路的话想想暴力就好了... 首先,比值最小就是确定最小值后最大值最小: 怎样确定最 ...