# 【bzoj1787】[Ahoi2008]Meet 紧急集合

## 1787: [Ahoi2008]Meet 紧急集合

Time Limit: 20 Sec  Memory Limit: 162 MB
Submit: 2466  Solved: 1117
[Submit][Status][Discuss]

6 4
1 2
2 3
2 4
4 5
5 6
4 5 6
6 3 1
2 4 4
6 6 6

## Sample Output

5 2
2 5
4 1
6 0

【题解】

 1 #include<iostream>
2 #include<cstdio>
3 #include<cstring>
4 #include<cstdlib>
5 #include<ctime>
6 #include<cmath>
7 #include<algorithm>
8 using namespace std;
9 #define MAXN 500010
10 struct node{int y,next;}e[MAXN*2];
13 {
14     int x=0,f=1;  char ch=getchar();
15     while(!isdigit(ch))  {if(ch=='-')  f=-1;  ch=getchar();}
16     while(isdigit(ch))  {x=x*10+ch-'0';  ch=getchar();}
17     return x*f;
18 }
20 void dfs(int x,int fa)
21 {
22     anc[x][0]=f[x];
23     for(int i=1;i<=20;i++)  anc[x][i]=anc[anc[x][i-1]][i-1];
25         if(e[i].y!=fa)
26         {
27             deep[e[i].y]=deep[x]+1;
28             f[e[i].y]=x;
29             dfs(e[i].y,x);
30         }
31 }
32 int lca(int x,int y)
33 {
34     if(deep[x]<deep[y])  swap(x,y);
35     for(int i=20;i>=0;i--)  if(deep[anc[x][i]]>=deep[y])  x=anc[x][i];
36     if(x==y)  return x;
37     for(int i=20;i>=0;i--)  if(anc[x][i]!=anc[y][i])  x=anc[x][i],y=anc[y][i];
38     return f[x];
39 }
40 int cal(int a,int b,int c)  {if(a==b)return c;else if(a==c)return b;else return a;}
41 int dis(int x,int y)  {int t=lca(x,y);return deep[x]+deep[y]-2*deep[t];}
42 int main()
43 {
44     //freopen("cin.in","r",stdin);
45     //freopen("cout.out","w",stdout);
48     deep[1]=1;  dfs(1,0);
49     for(int i=1;i<=m;i++)
50     {
52         int a=lca(x,y),b=lca(x,z),c=lca(y,z);
53         int p=cal(a,b,c);
54         ans=dis(x,p)+dis(y,p)+dis(z,p);
55         printf("%d %d\n",p,ans);
56     }
57     return 0;
58 }

posted @ 2016-10-18 11:13  chty  阅读(186)  评论(0编辑  收藏  举报