PAT甲级1151 LCA in a Binary Tree (30 分):[C++题解]LCA、最低公共祖先、哈希表映射
文章目錄
- 題目分析
- 題目鏈接
題目分析
來(lái)源:acwing
分析:
和下面這道題幾乎是同一題:PAT甲級(jí)1143 Lowest Common Ancestor (30 分):[C++題解]LCA、最低公共祖先
這道題先是根據(jù)給定的中序遍歷和先序遍歷,建樹。
建樹的時(shí)候需要用到點(diǎn)的深度和每個(gè)點(diǎn)的父節(jié)點(diǎn)是什么。
然后是找LCA,有很多優(yōu)秀的算法,這里使用樸素做法,O(n)復(fù)雜度。思想是:兩個(gè)結(jié)點(diǎn)a和b,深度深的往上等于它的父節(jié)點(diǎn);如果兩者位于同一層,任意一個(gè)往上走等于它的父親,直到兩者相等。相等時(shí)就是最低公共祖先。
while( a != b){if(depth[a] < depth[b]) b =p[b];else a = p[a]; }本題需要注意的使用哈希表pos映射進(jìn)行離散化到0~n-1,seq數(shù)組記錄映射之前的數(shù)。因?yàn)轭}目給的數(shù)據(jù)是int范圍內(nèi)的,不離散化查找容易超時(shí)。離散化代碼:
//讀入中序for(int i = 0; i< n; i++) {cin >> seq[i]; //讀入中序pos[seq[i]] =i; //保存中序序列映射后的值in[i] =i; //中序遍歷映射到0~n-1}//讀入前序for(int i = 0; i<n; i++) {cin >> pre[i];pre[i] = pos[pre[i]]; //前序遍歷進(jìn)行映射}ac代碼
#include<bits/stdc++.h> using namespace std; const int N = 10010;int in[N],pre[N],seq[N]; int n, m; unordered_map<int,int> pos; int p[N],depth[N];//根據(jù)中序遍歷和前序遍歷建樹 int build( int il ,int ir ,int pl ,int pr ,int d){int root = pre[pl];int k = root;depth [root] = d;if(il < k) p[build(il , k -1 , pl+1, pl+1 + k -1 -il , d+1)] = root;if( k< ir) p[build(k+1,ir ,pl+ k - il+1, pr,d+1)] =root ;return root; }int main(){cin >> m >> n;//讀入中序for(int i = 0; i< n; i++) {cin >> seq[i];pos[seq[i]] =i;in[i] =i; //中序遍歷映射到0~n-1}//讀入前序for(int i = 0; i<n; i++) {cin >> pre[i];pre[i] = pos[pre[i]];}build( 0, n-1, 0, n-1, 0);while(m--){int a, b;cin >> a >> b;if(pos.count(a) && pos.count(b)){a =pos[a],b= pos[b];int x =a, y =b;while(a != b){if(depth[a] > depth[b]) a =p[a];else b=p[b];}if(a != x && b!= y) printf("LCA of %d and %d is %d.\n",seq[x],seq[y],seq[a]);else if(a == x) printf("%d is an ancestor of %d.\n",seq[a],seq[y]);else printf("%d is an ancestor of %d.\n",seq[a],seq[x]);}else if(pos.count(a) == 0 && pos.count(b) ==0) printf("ERROR: %d and %d are not found.\n",a,b);else if(pos.count(a) ==0)printf("ERROR: %d is not found.\n",a);else printf("ERROR: %d is not found.\n",b);} }題目鏈接
PAT甲級(jí)1151 LCA in a Binary Tree (30 分)
https://www.acwing.com/problem/content/1646/
總結(jié)
以上是生活随笔為你收集整理的PAT甲级1151 LCA in a Binary Tree (30 分):[C++题解]LCA、最低公共祖先、哈希表映射的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: PAT甲级1130 Infix Expr
- 下一篇: PAT甲级1060 Are They E