【1143】Lowest Common Ancestor (30分)

简介: 【1143】Lowest Common Ancestor (30分)【1143】Lowest Common Ancestor (30分)
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>  
#include<map>
#include<vector>
#include<queue> 
#include<map>
using namespace std;  
map<int,bool> mp;
PS:map<int,bool> mp用来标记出现的结点,遍历 一遍pre数组~vector,如果pre[i]满足BST的要求(if内)则break
int main(){   
  int m,n,u,v,a;
  scanf("%d %d",&m,&n);//m次查询,n个结点
  vector<int> pre(n);
  for(int i=0;i<n;i++){
    scanf("%d",&pre[i]);//vector存入二叉搜索树的前序遍历序列
    mp[pre[i]]=true;//标记树中所有出现过的结点
  }
  for(int i=0;i<m;i++){//m次查询
    scanf("%d %d",&u,&v);//查询u和v的LCA
    for(int j=0;j<n;j++){//n个结点
      a=pre[j];
      if((a>=u && a<=v)||(a>=v && a<=u)) break;
      //BST:每个节点的值大于(小于)其!!任意!!左侧子节点的值,
      //小于(大于)其任意右节点的值,这个a是唯一的!(如果存在的话)
    }
    if(mp[u]==false && mp[v]==false)
      printf("ERROR: %d and %d are not found.\n",u,v);
    else if(mp[u]==false || mp[v]==false)
      printf("ERROR: %d is not found.\n",mp[u]==false?u:v);
    else if(a==u || a==v)
      printf("%d is an ancestor of %d.\n",a,a==u?v:u);
    else 
      printf("LCA of %d and %d is %d.\n",u,v,a);
  }
  system("pause");
    return 0;   
}
相关文章
Leetcode 236. Lowest Common Ancestor of a Binary Tree
根据LCA的定义,二叉树中最小公共祖先就是两个节点p和q最近的共同祖先节点,LCA的定义没什么好解释的,主要是这道题的解法。
43 0
|
存储 机器学习/深度学习 C++
【PAT甲级 - C++题解】1143 Lowest Common Ancestor
【PAT甲级 - C++题解】1143 Lowest Common Ancestor
78 0
CF1454 E. Number of Simple Paths (基环树 拓扑排序)
CF1454 E. Number of Simple Paths (基环树 拓扑排序)
94 0
PAT (Advanced Level) Practice - 1119 Pre- and Post-order Traversals(30 分)
PAT (Advanced Level) Practice - 1119 Pre- and Post-order Traversals(30 分)
126 0
PAT (Advanced Level) Practice - 1119 Pre- and Post-order Traversals(30 分)
PAT (Advanced Level) Practice - 1143 Lowest Common Ancestor(30 分)
PAT (Advanced Level) Practice - 1143 Lowest Common Ancestor(30 分)
121 0
Data Structures and Algorithms (English) - 6-6 Level-order Traversal(25 分)
Data Structures and Algorithms (English) - 6-6 Level-order Traversal(25 分)
103 0
PAT (Advanced Level) Practice - 1068 Find More Coins(30 分)
PAT (Advanced Level) Practice - 1068 Find More Coins(30 分)
115 0
HDOJ 2028 Lowest Common Multiple Plus(n个数的最小公倍数)
HDOJ 2028 Lowest Common Multiple Plus(n个数的最小公倍数)
129 0