PAT A1151 LCA in a Binary Tree (30 分)——二叉树,最小公共祖先(lca)
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.
Given any two nodes in a binary tree, 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 binary tree, respectively. In each of the following two lines, N distinct integers are given as the inorder and preorder traversal sequences of the binary tree, respectively. It is guaranteed that the binary tree can be uniquely determined by the input sequences. 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 Xis A and Y is the other node. If U or V is not found in the binary tree, 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
7 2 3 4 6 5 1 8
5 3 7 2 6 4 8 1
2 6
8 1
7 9
12 -3
0 8
99 99
Sample Output:
LCA of 2 and 6 is 3.
8 is an ancestor of 1.
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
ERROR: 0 is not found.
ERROR: 99 and 99 are not found.
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
#include <set>
using namespace std;
const int maxn=;
int n,m,k;
int inorder[maxn],preorder[maxn];
struct node{
int data;
node* left;
node* right;
};
node* create(int prel,int prer,int inl,int inr){
if(prel>prer){
return NULL;
}
node* root=new node;
root->data=preorder[prel];
int k;
for(k=inl;k<=inr;k++){
if(inorder[k]==preorder[prel]){
break;
}
}
int numleft=k-inl;
root->left = create(prel+,prel+numleft,inl,k-);
root->right = create(prel+numleft+,prer,k+,inr);
return root;
}
bool findnode(int x){
for(int i=;i<m;i++){
if(preorder[i]==x) return true;
}
return false;
}
node* lca(node* root,int x1,int x2){
if(root==NULL)return NULL;
if(root->data==x1 || root->data==x2) return root;
node* left = lca(root->left,x1,x2);
node* right = lca(root->right,x1,x2);
if(left && right) return root;
else if(left==NULL) return right;
else return left;
}
int main(){
scanf("%d %d",&n,&m);
for(int i=;i<m;i++){
int c1;
scanf("%d",&c1);
inorder[i]=c1;
}
for(int i=;i<m;i++){
int c1;
scanf("%d",&c1);
preorder[i]=c1;
}
node *root=create(,m-,,m-);
for(int i=;i<n;i++){
int x1,x2;
scanf("%d %d",&x1,&x2);
if(!findnode(x1) && !findnode(x2)){
printf("ERROR: %d and %d are not found.\n",x1,x2);
}
else if(!findnode(x1)) printf("ERROR: %d is not found.\n",x1);
else if(!findnode(x2)) printf("ERROR: %d is not found.\n",x2);
else{
node* res = lca(root,x1,x2);
if(res->data == x1) printf("%d is an ancestor of %d.\n",x1,x2);
else if(res->data == x2) printf("%d is an ancestor of %d.\n",x2,x1);
else printf("LCA of %d and %d is %d.\n",x1,x2,res->data);
}
}
}
注意点:lca居然可以迭代做出来,实在是厉害,看了好久终于看懂了一点吧,考前要再背一下。一开始想的是把指定点的祖先都获得存在一个vector里,然后从后往前比较两个vector,第一个相同的就是他们的lca,但调试了半天一直报错,vector的index超出范围,不知道为什么,总感觉是对的,代码贴在下面,有大佬看到还请指点一下。
第二点的话就是二叉树的建立一定要熟悉,虽然这道题可以不用建树就做出来。
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
#include <set>
using namespace std;
const int maxn = ;
int n, m, k, q = ;
int inorder[maxn], preorder[maxn];
vector<int> v, v1[];
struct node {
int data;
node* left;
node* right;
};
node* create(int prel, int prer, int inl, int inr) {
if (prel > prer) {
return NULL;
}
node* root = new node;
root->data = preorder[prel];
int k;
for (k = inl; k <= inr; k++) {
if (inorder[k] == preorder[prel]) {
break;
}
}
int numleft = k - inl;
root->left = create(prel + , prel + numleft, inl, k - );
root->right = create(prel + numleft + , prer, k + , inr);
return root;
}
void search(node* root, int x) {
if (root == NULL) return;
v.push_back(root->data);
if (root->data == x) {
for (int i = ; i < v.size(); i++) {
v1[q].push_back(v[i]);
}
v.pop_back();
return;
}
search(root->left, x);
search(root->right, x);
v.pop_back();
}
int main() {
scanf("%d %d", &n, &m);
for (int i = ; i < m; i++) {
int c1;
scanf("%d", &c1);
inorder[i] = c1;
}
for (int i = ; i < m; i++) {
int c1;
scanf("%d", &c1);
preorder[i] = c1;
}
node *root = new node;
root = create(, m - , , m - );
for (int i = ; i < n; i++) {
int x1, x2;
scanf("%d %d", &x1, &x2);
v1[].clear();
v1[].clear();
v.clear();
q = ;
search(root, x1);
q = ;
v.clear();
search(root, x2);
if (v1[].empty() && v1[].empty()) {
printf("ERROR: %d and %d are not found.\n", x1, x2);
}
else if (v1[].empty()) printf("ERROR: %d is not found.\n", x1);
else if (v1[].empty()) printf("ERROR: %d is not found.\n", x2);
else {
for (int j = v1[].size() - ; j >= ; j++) {
for (int k = v1[].size() - ; k >= ; k++) {
if (v1[][j] == v1[][k]) {
if (j == v1[].size() - ) printf("%d is an ancestor of %d.\n", x1, x2);
else if (k == v1[].size() - ) printf("%d is an ancestor of %d.\n", x2, x1);
else printf("LCA of %d and %d is %d.\n", x1, x2, v1[][j]);
}
}
}
}
}
}
PAT A1151 LCA in a Binary Tree (30 分)——二叉树,最小公共祖先(lca)的更多相关文章
- PAT Advanced 1151 LCA in a Binary Tree (30) [树的遍历,LCA算法]
题目 The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both ...
- PAT-2019年冬季考试-甲级 7-4 Cartesian Tree (30分)(最小堆的中序遍历求层序遍历,递归建树bfs层序)
7-4 Cartesian Tree (30分) A Cartesian tree is a binary tree constructed from a sequence of distinct ...
- PAT甲级|1151 LCA in a Binary Tree 先序中序遍历建树 lca
给定先序中序遍历的序列,可以确定一颗唯一的树 先序遍历第一个遍历到的是根,中序遍历确定左右子树 查结点a和结点b的最近公共祖先,简单lca思路: 1.如果a和b分别在当前根的左右子树,当前的根就是最近 ...
- Network-POJ3694(最小公共祖先LCA+Tarjin)
http://poj.org/problem?id=3694 这一题 为什么要找最小祖先呢 当两个节点连到一块的时候 找最小公共节点就相当于找强连通分支 再找最小公共节点的过程中直到找到 这个过 ...
- 【PAT甲级】1110 Complete Binary Tree (25分)
题意: 输入一个正整数N(<=20),代表结点个数(0~N-1),接着输入N行每行包括每个结点的左右子结点,'-'表示无该子结点,输出是否是一颗完全二叉树,是的话输出最后一个子结点否则输出根节点 ...
- Jamie and Tree (dfs序 + 最近公共祖先LCA)
题面 题解 我们求它子树的权值和,一般用dfs序把树拍到线段树上做. 当它换根时,我们就直接把root赋值就行了,树的结构不去动它. 对于第二个操作,我们得到的链和根的相对位置有三种情况: 设两点为A ...
- PAT_A1151#LCA in a Binary Tree
Source: PAT A1151 LCA in a Binary Tree (30 分) Description: The lowest common ancestor (LCA) of two n ...
- 【PAT 甲级】1151 LCA in a Binary Tree (30 分)
题目描述 The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has bo ...
- PAT 1151 LCA in a Binary Tree[难][二叉树]
1151 LCA in a Binary Tree (30 分) The lowest common ancestor (LCA) of two nodes U and V in a tree is ...
随机推荐
- Java基础——Oracle(四)
一.Sql * plus 常用命令 1.关于登录,连接的几个命令 1) conn[nect] //例 conn system/manager 用法 conn 用户名/密码 @网络服务名 (as sy ...
- inheritCombinedParasitic.js
// 寄生组合式继承 // 其基本思路是通过借用构造函数来继承属性,通过原型链的混成形式来继承方法,就是为了不必为了子类型的原型去调用父类型的构造函数 function inheritPrototyp ...
- python之编码和解码
编码: 1. ascii. 有: 数字, 字母, 特殊字符. 8bit 1byte 128 最前面是0 2. gbk. 包含: ascii, 中文(主要), 日文, 韩文, 繁体文字. 16bit, ...
- JMeter JMeter自身运行性能优化
JMeter自身运行性能优化 by:授客 QQ:1033553122 测试环境 apache-jmeter-2.13 1. 问题描述 单台机器的下JMeter启动较大线程数时可能会出现运行 ...
- MVC与单元测试实践之健身网站(完)-备案与部署
主页-http://www.zhixin9001.cn/Home/Introduce GitHub- https://github.com/zhixin9001/Fitness 这是关于Fit网站的最 ...
- 《Inside C#》笔记(十三) 多线程 上
通过将一个任务划分成多个任务分别在独立的线程执行可以更有效地利用处理器资源并节省时间.但如果不合理地使用多线程,反而会带来种种问题并拖慢运行速度. 一 线程基础 a)线程与多任务 一个线程就是一个处理 ...
- TraceView工具的使用
一.TraceView工具如何使用 TraceView有4种启动/关闭分析方式: (1) 第一种使用方法演示 1. 选择跟踪范围 在想要根据的代码片段之间使用以下两句代码 Debug.startMet ...
- (后台)java 读取excel 文件 Unable to recognize OLE stream 错误
原因:不支出读取 excel 2007 文件(*.xlsx).只支持 excel 2003 (*.xls). 光修改文件后缀不行,需要文件另存(或者导出)为 .xls Excel 1997-2004 ...
- aws linux主机root帐号登录
默认情况下,aws主机必须使用pem密码文件并且以ec2-user用户登录系统,之后很多操作都必须用sudo来以root权限执行操作,显得比较麻烦. 以下来自知乎的一个问答,亲测ok ## AWS E ...
- My strength (C-A-R)
My strength: I am good at problem resolving Challenge In the first year when I come to America I pas ...