PAT A1151 LCA in Binary Tree
利用树的前序和中序递归判定最小公共祖先~
直接根据两个序列递归处理~
#include<bits/stdc++.h> using namespace std; const int maxn=10010; int N,M; int pre[maxn],in[maxn]; unordered_map<int,int> pos; void lca (int inL,int inR,int preRoot,int a,int b) { if (inL>inR) return; int inRoot=pos[pre[preRoot]]; int aIn=pos[a]; int bIn=pos[b]; if ((aIn>inRoot&&bIn<inRoot)||(aIn<inRoot&&bIn>inRoot)) printf ("LCA of %d and %d is %d.\n",a,b,in[inRoot]); else if (aIn>inRoot&&bIn>inRoot) lca (inRoot+1,inR,preRoot+inRoot-inL+1,a,b); else if (aIn<inRoot&&bIn<inRoot) lca (inL,inRoot-1,preRoot+1,a,b); else if (aIn==inRoot) printf ("%d is an ancestor of %d.\n",a,b); else if (bIn==inRoot) printf ("%d is an ancestor of %d.\n",b,a); } int main () { scanf ("%d %d",&M,&N); for (int i=1;i<=N;i++) { scanf ("%d",&in[i]); pos[in[i]]=i; } for (int i=1;i<=N;i++) scanf ("%d",&pre[i]); int a,b; for (int i=0;i<M;i++) { scanf ("%d %d",&a,&b); if (pos[a]==0&&pos[b]==0) printf ("ERROR: %d and %d are not found.\n",a,b); else if (pos[a]==0) printf ("ERROR: %d is not found.\n",a); else if (pos[b]==0) printf ("ERROR: %d is not found.\n",b); else lca (1,N,1,a,b); } return 0; }
也可以根据树建图,跑lca算法
#include<bits/stdc++.h> using namespace std; const int maxn=10010; struct node { int data; node * left; node * right; }; int M,N; int pre[maxn],in[maxn]; unordered_map<int,int> pos; int father[maxn*100]; int depth[maxn*100]; node * create (int preL,int preR,int inL,int inR) { if (preL>preR) return NULL; node * root=new node; root->data=pre[preL]; int k; for (k=inL;k<=inR;k++) if (in[k]==pre[preL]) break; int numLeft=k-inL; root->left=create(preL+1,preL+numLeft,inL,k-1); if (root->left!=NULL) father[root->left->data]=root->data; root->right=create(preL+numLeft+1,preR,k+1,inR); if (root->right!=NULL) father[root->right->data]=root->data; return root; } void bfs (node * root) { queue<node *> q; q.push(root); depth[root->data]=1; while (!q.empty()) { node * now=q.front(); q.pop(); if (now->left) {q.push(now->left);depth[now->left->data]=depth[now->data]+1;} if (now->right) {q.push(now->right);depth[now->right->data]=depth[now->data]+1;} } } void lca (int u,int v) { int tu=u; int tv=v; while (depth[tu]<depth[tv]) { tv=father[tv]; } while (depth[tu]>depth[tv]) { tu=father[tu]; } while (tu!=tv) { tu=father[tu]; tv=father[tv]; } if (tu==u) printf ("%d is an ancestor of %d.\n",u,v); else if (tu==v) printf ("%d is an ancestor of %d.\n",v,u); else printf ("LCA of %d and %d is %d.\n",u,v,tu); } int main () { scanf ("%d %d",&M,&N); for (int i=1;i<=N;i++) father[i]=i; for (int i=1;i<=N;i++) { scanf ("%d",&in[i]); pos[in[i]]=i; } for (int i=1;i<=N;i++) scanf ("%d",&pre[i]); node * root=create(1,N,1,N); bfs(root); int u,v; for (int i=0;i<M;i++) { scanf ("%d %d",&u,&v); if (pos[u]==0&&pos[v]==0) printf ("ERROR: %d and %d are not found.\n",u,v); else if (pos[u]==0||pos[v]==0) printf ("ERROR: %d is not found.\n",pos[u]==0?u:v); else lca (u,v); } return 0; }