poj1330 Nearest Common Ancestors

题目链接:..G20过了再补

题目大意:求最近公共祖先...水..


题解:倍增LCA/树剖

就是练模版的题...话说看了一下,我的树剖比倍增还快了那么一丢丢..

注意:不是无根树啊233

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
#define maxn 20100

struct node
{
	int x,y,next;
}a[maxn];int len,first[maxn];
void ins(int x,int y)
{
	len++;
	a[len].x=x;a[len].y=y;
	a[len].next=first[x];first[x]=len;
}
int fa[maxn],son[maxn],dep[maxn];
int tot[maxn],top[maxn];
void dfs1(int x)
{
	son[x]=0;tot[x]=1;
	for (int k=first[x];k!=-1;k=a[k].next)
	{
		int y=a[k].y;
		if (y!=fa[x])
		{
			fa[y]=x;
			dep[y]=dep[x]+1;
			dfs1(y);
			if (tot[son[x]]<tot[y]) son[x]=y;
			tot[x]+=tot[y];
		}
	}
}
void dfs2(int x,int tp)
{
	top[x]=tp;
	if (son[x]!=0) dfs2(son[x],tp);
	for (int k=first[x];k!=-1;k=a[k].next)
	{
		int y=a[k].y;
		if (y!=fa[x] && y!=son[x]) dfs2(y,y);
	}
}
int lca(int x,int y)
{
	int ty=top[y],tx=top[x];
	while (tx!=ty)
	{
		if (dep[tx]>dep[ty])
		{
			int tt=tx;tx=ty;ty=tt;
			tt=x;x=y;y=tt;
		}y=fa[ty];ty=top[y];
	}
	if (x==y) return x;
	else
	{
		if (dep[x]>dep[y])
		{
			int tt=x;x=y;y=tt;
		}
		return x;
	}
}
int main()
{
	//freopen("a.in","r",stdin);
	//freopen("a.out","w",stdout);
	int T,n,x,y,i,rt;
	scanf("%d",&T);
	while (T--)
	{
		len=0;memset(first,-1,sizeof(first));
		scanf("%d",&n);rt=(1+n)*n/2;
		for (i=1;i<n;i++)
		{
			scanf("%d%d",&x,&y);
			ins(x,y);ins(y,x);
			rt-=y;
		}
		fa[rt]=0;dep[rt]=0;dfs1(rt);
		dfs2(rt,rt);
		scanf("%d%d",&x,&y);
		printf("%d
",lca(x,y));
	}
	return 0;
}


原文地址:https://www.cnblogs.com/Euryale-Rose/p/6527871.html