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

30 篇文章 0 订阅
8 篇文章 0 订阅
D e s c r i p t i o n Description Description

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

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


S o l u t i o n Solution Solution

L C A LCA LCA d f s dfs dfs


C o d e ( L C A ) Code(LCA) 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");
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值