BZOJ P1832[AHOI2008]聚会

双倍经验的水题

虽说讲道理不应该刷,但是练练lca模板还是不错的

#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
int head[1000003],to[1000003],nex[1000003],tot;
int depth[500003],in[500003],out[500003];
int chuo=0,n,m;
int f[500003][20];
void add(int u,int v){
	to[++tot]=v;
	nex[tot]=head[u];
	head[u]=tot;
}
int dfs(int fa,int now,int dep){
	depth[now]=dep;
	in[now]=++chuo;
	f[now][0]=now;
	for(int i=head[now];i;i=nex[i]){
		if(to[i]!=fa){
			dfs(now,to[i],dep+1);
		}
	}
	out[now]=++chuo;
}
bool pd(int x,int y){
	if(in[x]<=in[y]&&out[x]>=out[y]){
		return true;
	}
	return false;
}
int lca(int x,int y){
	if(pd(x,y)){
		return x;
	}
	if(pd(y,x)){
		return y;
	}
	int k=x;
	for(int i=30;i>=0;i--){
		if(!pd(f[k][i],y)){
			k=f[k][i];
		}
	}
	return f[k][0];
}
int ju(int a,int b){
	int x=lca(a,b);
	return(2*depth[x]-depth[a]-depth[b]);
}
int main(){
	cin>>n>>m;
	for(int i=1;i<=n-1;i++){
		int u,v;
		cin>>u>>v;
		add(u,v);
		add(v,u);
	}
	dfs(0,1,1);
	for(int i=1;i<=n;i++){
		for(int j=1;j<=30;j++){
			f[i][j]=f[f[i][j-1]][j-1];
		}
	}
	for(int i=1;i<=m;i++){
		int a,b,c;
		cin>>a>>b>>c;
		int lca1=lca(a,b);
		int lca2=lca(a,c);
		int lca3=lca(b,c);
		if(lca1==lca2){
			cout<<lca3<<" "<<-ju(lca3,a)-depth[lca3]*2+depth[b]+depth[c]<<endl;
			continue;
		}
		if(lca2==lca3){
			cout<<lca1<<" "<<-ju(lca1,a)-depth[lca1]*2+depth[a]+depth[b]<<endl;
			continue;
		}
		if(lca1==lca3){
			cout<<lca2<<" "<<-ju(lca2,a)-depth[lca2]*2+depth[a]+depth[c]<<endl;
			continue;
		}
	}
	//cout<<endl<<lca(1,3)<<lca(3,6)<<lca(1,6);
	return 0;
}
/*
in:
6 4
1 2
2 3
2 4
4 5
5 6
4 5 6
6 3 1
2 4 4
6 6 6
out:
5 2
2 5
4 1
6 0
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值