PAT 1151

题目 : LCA in a Binary Tree

分值 : 30
难度 : 水题
思路 : 整合下标法进行LCA巧解
坑点 : 精简做法,一行一分.

具体代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <vector>
#include <map>
using namespace std;
map<int ,bool> flag;
map<int ,int > in ;
vector<int> pre;
int main() {
int M ,N ,t ,t2;
cin >> M >> N ; pre.resize(N+1);
for(int i = 0 ; i <N ; i++) {
cin >>t ;
in[t] = i ; flag[t] = true ;
}
for(int i = 0 ; i< N ; i++)
cin >>pre[i] ;
for(int i = 0 ; i< M ;i++){
cin >> t>> t2 ;
if(flag[t] && !flag[t2]) printf("ERROR: %d is not found.\n",t2);
else if(!flag[t] && flag[t2]) printf("ERROR: %d is not found.\n",t);
else if(!flag[t] && !flag[t2]) printf("ERROR: %d and %d are not found.\n",t,t2);
else{
int c1 = in[t] , c2 =in[t2];
for(int j = 0 ; j< pre.size() ; j++){
int cj = in[pre[j]];
if(cj==c1){printf("%d is an ancestor of %d.\n",t,t2);break;}
else if(cj==c2){printf("%d is an ancestor of %d.\n",t2,t);break;}
else if((cj - c1)*(cj - c2) < 0){
printf("LCA of %d and %d is %d.\n",t,t2,pre[j]);
break ;
}
}
}
}
}