BZOJ 1787: [Ahoi2008] Meet emergency collection

Title Description

Happy island has a very fun game, called "emergency collection." Dispersed island wait N points, N-1 with a road connected to them, are each connected to a two road holding point, and can be traveled through all these points waiting path through a road from one point to another a point to spend a coin.

People participate in the game trio, beginning, all staff are waiting for any scattered in various points (each point while allowing more than one person waiting), every person with enough game currency (to pay for use of roads costs), maps (road connections between the case marked the holding point) and dialogue machine (for members of the Contact group and with). After collection of the trumpet, the rapid link between members of each group, all the groups themselves understand the holding point where the members, quickly determine a waiting assembly point of N points, all members of the group will be set in the set point, collection used the least expensive group will be the winner of the game.

Small cocoa and his friends invite you to join the game, to you to choose the set point, clever you can accomplish this task, to help small cocoa win the game?

 

 

 

answer: 

Code:

#include<bits/stdc++.h>
#define maxn 600000 
using namespace std; 
void setIO(string s)
{
	string in=s+".in"; 
	freopen(in.c_str(),"r",stdin); 
}
int edges,n,Q; 
int hd[maxn],to[maxn<<1],nex[maxn<<1],dep[maxn],siz[maxn],hson[maxn],fa[maxn],top[maxn];  
void add(int u,int v)
{
	nex[++edges]=hd[u],hd[u]=edges,to[edges]=v; 
}
void dfs1(int u,int ff)
{
	fa[u]=ff,dep[u]=dep[ff]+1,siz[u]=1; 
	for(int i=hd[u];i;i=nex[i])
	{
		int v=to[i];
		if(v==ff) continue; 
		dfs1(v,u); 
		siz[u]+=siz[v]; 
		if(siz[v]>siz[hson[u]]) hson[u]=v; 
	}
}
void dfs2(int u,int tp)
{
	top[u]=tp; 
	if(hson[u]) dfs2(hson[u],tp); 
	for(int i=hd[u];i;i=nex[i])
	{
		int v=to[i]; 
		if(v==fa[u]||v==hson[u]) continue; 
		dfs2(v,v); 
	}
}
int LCA(int x,int y)
{
	while(top[x]^top[y]) dep[top[x]] > dep[top[y]] ? x = fa[top[x]] : y = fa[top[y]]; 
	return dep[x] < dep[y] ? x : y; 
}
int Getdis(int x,int y)
{
	return dep[x] + dep[y] - (dep[LCA(x,y)]<<1); 
}
int main()
{
	// setIO("input"); 
	scanf("%d%d",&n,&Q);
	for(int i=1,u,v;i<n;++i)  
	{
		scanf("%d%d",&u,&v); 
		add(u,v), add(v,u); 
	}
	dfs1(1,0); 
	dfs2(1,1);    
	int u,v,t; 
	while(Q--)
	{
		scanf("%d%d%d",&u,&v,&t); 
		int d1=LCA(u,v),d2=LCA(u,t),cur,d3=LCA(v,t); 
		cur=dep[d1]<dep[d2]?d2:d1;
		cur=dep[cur]<dep[d3]?d3:cur; 
		printf("%d %d\n",cur,Getdis(u,cur)+Getdis(v,cur)+Getdis(t,cur)); 
	}
	return 0; 
}

  

 

Guess you like

Origin www.cnblogs.com/guangheli/p/11013912.html