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"