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. N天学习一个Linux命令之top

    用途 查看机器负载以及进程资源占用情况,linux系统性能分析工具 用法 top -hv | -abcHimMsS -d delay -n iterations -p pid [, pid ...] ...

  2. Swift: 一句话获取虚拟机上APP所在的目录

    在XCode6上,虚拟机的App的存放位置发生了变化,通过下面语句,我们可以立即获得其所在的位置: println(NSTemporaryDirectory())

  3. Codeforces Round #305 (Div. 2) E题(数论+容斥原理)

    E. Mike and Foam time limit per test 2 seconds memory limit per test 256 megabytes input standard in ...

  4. POJ2584_T-Shirt Gumbo(二分图多重最大匹配/最大流)

    解题报告 http://blog.csdn.net/juncoder/article/details/38239367 题目传送门 题意: X个參赛选手,每一个选手有衣服大小的范围,5种大小的队服,求 ...

  5. 极光推送案例-PushExample-Jpush

    ssh - maven - java项目-极光注冊id完毕推送 这是我学习时的步骤: 1:去极光推送平台注冊账号,自己能够去注冊(一般公司会帮助完毕注冊) 地址:https://www.jpush.c ...

  6. oc37--类工厂方法

    // // Person.h #import <Foundation/Foundation.h> @interface Person : NSObject @property int ag ...

  7. 查看tensorflow pb模型文件的节点信息

    查看tensorflow pb模型文件的节点信息: import tensorflow as tf with tf.Session() as sess: with open('./quantized_ ...

  8. 数据预处理之Minkowski距离计算

    template <class T1, class T2> double Minkowski(const std::vector<T1> &inst1, const s ...

  9. 10 Future Web Trends 十大未来互联网趋势

    转载自:http://blog.sina.com.cn/s/blog_4be577310100ajpb.html 我们很满意自己进入的当前网络纪元,通常被称为Web 2.0.这个阶段互联网的特征包括搜 ...

  10. python 4:str.lstrip()、str.rstrip()、str.strip()(分别去除首空格,尾空格,首尾空格;不改变原有变量,除非赋给)

    name = " Hello,World! Hello,Python! " print(name + "检测行末空格的") print(name.lstrip( ...