POJ 1330:nearest Common Ancestors "LCA"

Source: Internet
Author: User

The question is: Well, give you a tree and two points and ask you what the LCA of these two points is

Idea: The template problem of LCA, it is important to note that when merging with the collection is not random, but the leaf node to the parent node

#include <cstdio>

#include <string.h>

#include <iostream>

#include <algorithm>

#include <math.h>

#define MAXN 10002

#define MOD 1000000007

using namespace Std;

int HEAD[MAXN],POINT[MAXN],NEXT[MAXN],FATHER[MAXN];

int now=0,in[maxn],finish=0;

BOOL VISIT[MAXN];

inline int Read ()

{

int X=0;char Ch=getchar ();

while (ch< ' 0 ' | | Ch> ' 9 ') Ch=getchar ();

while (ch>= ' 0 ' &&ch<= ' 9 ') {x=x*10+ch-' 0 '; Ch=getchar ();}

return x;

}

void Add (int x,int y)

{

NEXT[++NOW]=HEAD[X];

Head[x]=now;

Point[now]=y;

}

int find (int x)

{

if (X==father[x]) return x;

Return Father[x]=find (Father[x]);

}

void Dfs (int k,int s,int t)

{

for (int i=head[k];i;i=next[i])

{

if (finish==1) return;

int u=point[i];

DFS (U,S,T);

int X=find (k), Y=find (U);

if (x!=y) father[y]=x;

}

Visit[k]=1;

if (k==s && visit[t]) {printf ("%d\n", find (t)); finish=1;}

else if (k==t && visit[s]) {printf ("%d\n", find (s)); finish=1;}

return;

}

int main ()

{

int tt,n,x,y,root,s,t;

scanf ("%d", &TT);

while (tt--)

{

now=finish=0;

N=read ();

for (int i=1;i<=n;i++) father[i]=i;

for (int i=1;i<n;i++)

{

X=read (), Y=read ();

Add (x, y);

in[y]++;

}

for (int i=1;i<=n;i++) if (in[i]==0) Root=i;else in[i]=0;

S=read (), T=read ();

DFS (ROOT,S,T);

int u=sizeof (int) * (n+3);

int v=sizeof (BOOL) * (N+3);

memset (VISIT,0,V);

memset (Head,0,u);

}

return 0;

}

POJ 1330:nearest Common Ancestors "LCA"

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.