LCA in a Binary Tree

    技术2022-07-11  109

    #include<iostream> #include<string> #include<vector> #include<algorithm> #include<map> using namespace std; int m,n; vector<int> in(1000000,0); vector<int> pre(1000000,0); map<int,int> pos; void lca(int inl,int inr,int preroot,int inroot,int a,int b){ if(inl > inr) return; inroot = pos[pre[preroot]]; int ina = pos[a],inb = pos[b]; if(ina<inroot && inb>inroot || inb<inroot && ina>inroot){ printf("LCA of %d and %d is %d.\n",a,b,pre[preroot]); } else if(ina < inroot && inb<inroot){ lca(inl,inroot-1,preroot+1,inroot,a,b); } else if(ina > inroot && inb>inroot){ lca(inroot+1,inr,preroot+1+(inroot-inl),inroot,a,b); } else if(ina == inroot){ printf("%d is an ancestor of %d.\n",a,b); } else if(inb == inroot){ printf("%d is an ancestor of %d.\n",b,a); } } int main(){ int a,b; cin>>m>>n; for(int i=1;i<=n;i++){ cin>>in[i]; pos[in[i]] = i; } for(int i=1;i<=n;i++) cin>>pre[i]; for(int i=0;i<m;i++){ cin>>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 && pos[b]!=0){ printf("ERROR: %d is not found.\n",a); } else if(pos[a]!=0 && pos[b]==0){ printf("ERROR: %d is not found.\n",b); } else{ lca(1,n,1,a,a,b); } } return 0; }

     

    Processed: 0.013, SQL: 9