2019.3.8 提高B组 T1 JZOJ 3054 祖孙询问

版权声明:虽然本蒟蒻很菜,但各位dalao转载请注明出处谢谢。 https://blog.csdn.net/xuxiayang/article/details/88361799

D e s c r i p t i o n Description

已知一棵 n n 个节点的有根树。有 m m 个询问。每个询问给出了一对节点的编号 x x y y ,询问 x x与 y y 的祖孙关系。

数据范围:对于100%的.据 n , m 40000 n,m≤40000 ,每个节点的编号都不超过40000。


S o l u t i o n Solution

L C A LCA d f s dfs


C o d e ( L C A ) Code(LCA)

#include<queue>
#include<cmath>
#include<cstdio>
#include<vector>
#include<cctype>
#include<algorithm>
using namespace std;int n,m,root,x,y,f[40001][17],dep[40001],mdep,t;
vector<int>g[40001];
bool vis[40001];
inline long long read()
{
    char c;int d=1;long long f=0;
    while(c=getchar(),!isdigit(c))if(c==45)d=-1;f=(f<<3)+(f<<1)+c-48;
    while(c=getchar(),isdigit(c)) f=(f<<3)+(f<<1)+c-48;
    return d*f;
}
inline void bfs()//求深度
{
	queue<int>q;
	q.push(root);vis[root]=true;
	while(q.size())
	{
		int x=q.front();q.pop();
		for(register int i=0;i<g[x].size();i++)
		{
			int y=g[x][i];
			if(!vis[y])
			{
				vis[y]=true;
				dep[y]=dep[x]+1;
				mdep=max(mdep,dep[y]);
				f[y][0]=x;
				q.push(y);
			}
		}
	}
	return;
}
inline int lca(int x,int y)//求x,y的LCA
{
	if(dep[x]<dep[y]) swap(x,y);
	for(register int i=16;i>=0;i--) 
	if(dep[x]-(1<<i)>=dep[y]) x=f[x][i];
	for(register int i=16;i>=0;i--)
	if(f[x][i]!=f[y][i])
	{
		x=f[x][i];
		y=f[y][i];
	}
	if(x==y) return x;
	return f[x][0];
}
signed main()
{
	n=read();
	for(register int i=1;i<=n;i++)
	{
		x=read();y=read();
		if(y<0) root=x;
		else g[x].push_back(y),g[y].push_back(x);
	}
	bfs();
	f[root][0]=-1;
	for(register int j=1;j<=floor(log(mdep)/log(2));j++)
	 for(register int i=1;i<=40000;i++)
	  if(f[i][j-1]>-1)f[i][j]=f[f[i][j-1]][j-1];else f[i][j]=-1;//预处理
	m=read();
	while(m--)
	{
		x=read();y=read();
		t=lca(x,y);
		if(t!=x&&t!=y) puts("0");
		if(t==x) puts("1");
		if(t==y) puts("2");
	}
}

猜你喜欢

转载自blog.csdn.net/xuxiayang/article/details/88361799
今日推荐