【JZOJ3054】祖孙询问【LCA】

题目大意:

题目链接:https://jzoj.net/senior/#main/show/3054
给出一棵有根树,询问xxyy的祖孙关系。


思路:

水题。
直接求一遍lcalca,然后如果lcalcaxxyy中的一个,那么xxyy就是有祖孙关系的,否则就没有祖孙关系。


代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int N=40010;
const int LG=20;
int n,m,x,y,tot,root,head[N],f[N][LG+1],dep[N];

struct edge
{
	int next,to;
}e[N*2];

void add(int from,int to)
{
	e[++tot].to=to;
	e[tot].next=head[from];
	head[from]=tot;
}

void dfs(int x,int fa)
{
	dep[x]=dep[fa]+1;
	f[x][0]=fa;
	for (int i=1;i<=LG;i++)
		f[x][i]=f[f[x][i-1]][i-1];
	for (int i=head[x];~i;i=e[i].next)
	{
		int v=e[i].to;
		if (v!=fa) dfs(v,x);
	}
}

int lca(int x,int y)
{
	if (dep[x]<dep[y]) swap(x,y);
	for (int i=LG;i>=0;i--)
		if (dep[f[x][i]]>=dep[y]) x=f[x][i];
	if (x==y) return x;
	for (int i=LG;i>=0;i--)
		if (f[x][i]!=f[y][i])
		{
			x=f[x][i];
			y=f[y][i];
		}
	return f[x][0];
}

int main()
{
	memset(head,-1,sizeof(head));
	scanf("%d",&n);
	for (int i=1;i<=n;i++)
	{
		scanf("%d%d",&x,&y);
		if (y==-1) root=x;
		else
		{
			add(x,y);
			add(y,x);
		}
	}
	dfs(root,0);
	scanf("%d",&m);
	while (m--)
	{
		scanf("%d%d",&x,&y);
		int LCA=lca(x,y);
		if (LCA==x) printf("1\n");
		else if (LCA==y) printf("2\n");
		else printf("0\n");
	}
	return 0;
}
posted @ 2019-03-09 10:55  全OI最菜  阅读(104)  评论(0编辑  收藏  举报