PAT A1151 LCA in Binary Tree

利用树的前序和中序递归判定最小公共祖先~

也可以建图跑lca算法~

#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;
}

猜你喜欢

转载自www.cnblogs.com/zhanglichen/p/12301646.html