POJ 1330 Nearest Common Ancestors (template title) (LCA) "multiplier"

Source: Internet
Author: User

< topic links >

Main topic:

Give a tree and ask the number of the nearest public ancestor of any two points.

Problem Solving Analysis:
LCA template problem, the following is the online multiplication algorithm solution.

1#include <cstdio>2#include <cstring>3#include <algorithm>4#include <cmath>5 using namespacestd;6 7 Const intN = 1e4+Ten;8 Const intINF =0x3f3f3f3f;9 structedge{Ten     intTo,next; One}edge[n<<1]; A intCnt,head[n]; - intdep[n],f[n][ *]; - intNinch[N]; the voidAddedge (intUintv) { -edge[++cnt].to=v,edge[cnt].next=Head[u]; -head[u]=CNT; - } + voidDfsintUintFA) {//mark the depth of all nodes -      for(intI=head[u];~i;i=Edge[i].next) { +         intv=edge[i].to; A         if(V==FA)Continue; at         if(!Dep[v]) { -dep[v]=dep[u]+1; -f[v][0]=u; - DFS (v,u); -         }      -     } in } - voidInit () {//preprocessing multiplication Arrays to      for(intj=1;(1&LT;&LT;J) <=n;j++) +          for(intI=1; i<=n;i++) -f[i][j]=f[f[i][j-1]][j-1]; the } * intLCA (intXinty) { $     if(dep[x]<Dep[y]) swap (x, y);Panax Notoginseng     intd=dep[x]-Dep[y]; -      for(intI=0;(d >>i)! =0; i++) the         if((d>>i) &1) x=F[x][i]; +     if(x==y)returnx; A      for(intI= -; i>=0; i--) the         if(f[x][i]!=F[y][i]) { +x=F[x][i]; -y=F[y][i]; $         } $     returnf[x][0]; - } - intMain () { the     intT;SCANF ("%d",&T); -      while(t--){Wuyiscanf"%d",&n); theCnt=0; -         intu,v; Wumemset (head,-1,sizeof(head)); -          for(intI=1; i<n;i++){             Aboutscanf"%d%d",&u,&v); $ Addedge (u,v); -             inch[v]++; -         } -memset (DEP,0,sizeof(DEP)); A         intRoot; +          for(intI=1; i<=n;i++) the             if(!inch[i]) root=i;//find the root of the tree -dep[root]=1; $DFS (root,-1); the init (); thescanf"%d%d",&u,&v); theprintf"%d\n", LCA (u,v)); the     } -     return 0; in}

2018-10-18

POJ 1330 Nearest Common Ancestors (template title) (LCA) "multiplier"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.