【BZOJ】【P1787】【AHOI2008】【Meet 紧急集合】【题解】【LCA】

传送门:www.lydsy.com/JudgeOnline/problem.php?id=1787

我会告诉你我不会LCA吗……于是蒟蒻写了链剖,于是A了……

Code:

#include<cstdio>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<vector>
#include<climits>
#include<cctype>
using namespace std;
const int maxn=500010;
typedef pair<int,int> pii;
vector<int>G[maxn];
void add(int u,int v){
	G[u].push_back(v);
	G[v].push_back(u);
}
int w[maxn],fa[maxn],son[maxn],siz[maxn],dep[maxn],top[maxn],z;
void dfs(int u){
	son[u]=0;siz[u]=1;
	for(int i=0;i<G[u].size();i++){
		int v=G[u][i];
		if(v!=fa[u]){
			fa[v]=u;
			dep[v]=dep[u]+1;
			dfs(v);
			if(siz[son[u]]<siz[v])son[u]=v;
			siz[u]+=siz[v];
		}
	}
}
void build(int u,int tp){
	w[u]=++z;top[u]=tp;
	if(son[u])build(son[u],tp);
	for(int i=0;i<G[u].size();i++){
		int v=G[u][i];
		if(v!=fa[u]&&v!=son[u])
			build(v,v);
	}
}
int len(int u,int v){
	return abs(dep[u]-dep[v]);
}
int lca(int u,int v){
	while(top[u]!=top[v]){
		if(dep[top[u]]>dep[top[v]])
			u=fa[top[u]];
		else
			v=fa[top[v]];
	}
	return dep[u]<dep[v]?u:v;
}
int n,m;
int getint(){
	int res=0,ok=0;char ch;
	while(1){
		ch=getchar();
		if(isdigit(ch)){
			res*=10;res+=ch-'0';ok=1;
		}else if(ok)break;
	}return res;
}
int main(){
	n=getint();m=getint();
	for(int i=1;i<n;i++){
		int u=getint(),v=getint();add(u,v);
	}
	dfs(1);build(1,1);
	while(m--){
		int a=getint(),b=getint(),c=getint();
		int ans=INT_MAX,pos,k;
  		int d=lca(a,b);
        int e=lca(d,c);
        if(dep[a]+dep[b]+dep[c]-dep[e]*2-dep[d]<ans)ans=dep[a]+dep[b]+dep[c]-dep[e]*2-dep[d],pos=d;
        d=lca(a,c);
        if(dep[a]+dep[b]+dep[c]-dep[e]*2-dep[d]<ans)ans=dep[a]+dep[b]+dep[c]-dep[e]*2-dep[d],pos=d;
        d=lca(b,c);
        if(dep[a]+dep[b]+dep[c]-dep[e]*2-dep[d]<ans)ans=dep[a]+dep[b]+dep[c]-dep[e]*2-dep[d],pos=d;
		printf("%d %d\n",pos,ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值