[BZOJ][P1787][AHOI 2008][Meet 비상집합][문제풀이][LCA]

1977 단어 bzoj성선
전송문: 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
",pos,ans); } return 0; }

좋은 웹페이지 즐겨찾기