bzoj 1787 Meet 紧急集合

Meet 紧急集合

 1 #include<cstdio>
2 #include<iostream>
3 #include<algorithm>
4 #define N 500010
5 #define M 1000010
6 using namespace std;
10     to[num]=false_to;
12 }
13 void dfs1(int x){
14     size[x]=1;
15     deep[x]=deep[father[x]]+1;
17         if(father[x]!=to[i]){
18             father[to[i]]=x;
19             dfs1(to[i]);
20             size[x]+=size[to[i]];
21         }
22 }
23 void dfs2(int x){
24     int mmax=0;
25     if(!top[x])
26         top[x]=x;
28         if(father[x]!=to[i]&&size[to[i]]>size[mmax])
29             mmax=to[i];
30     if(mmax){
31         top[mmax]=top[x];
32         dfs2(mmax);
33     }
35         if(father[x]!=to[i]&&to[i]!=mmax)
36             dfs2(to[i]);
37 }
38 int lca(int x,int y){
39     while(top[x]!=top[y]){
40         if(deep[top[x]]<deep[top[y]])
41             swap(x,y);
42         x=father[top[x]];
43     }
44     if(deep[x]<deep[y])return x;
45     return y;
46 }
47 int main(){
48     scanf("%d%d",&n,&m);
49     for(int i=1;i<n;++i){
50         scanf("%d%d",&a,&b);
53     }
54     dfs1(1);
55     dfs2(1);
56     for(int i=1;i<=m;++i){
57         scanf("%d%d%d",&a,&b,&c);
58         ans=0;
59         c1=lca(a,b);
60         c2=lca(a,c);
61         c3=lca(b,c);
62         if(c1==c2&&c2==c3){
63             ans=abs(deep[c1]-deep[a])+abs(deep[c1]-deep[b])+abs(deep[c1]-deep[c]);
64             printf("%d %d\n",c1,ans);
65         }
66         else
67             if(c1==c2){
68                 ans+=deep[b]+deep[c]-deep[c3]*2;
69                 ans+=deep[c3]+deep[a]-deep[c1]*2;
70                 printf("%d %d\n",c3,ans);
71             }
72         else
73             if(c1==c3){
74                 ans+=deep[a]+deep[c]-deep[c2]*2;
75                 ans+=deep[c2]+deep[b]-deep[c1]*2;
76                 printf("%d %d\n",c2,ans);
77             }
78         else{
79             ans+=deep[a]+deep[b]-deep[c1]*2;
80             ans+=deep[c1]+deep[c]-deep[c2]*2;
81             printf("%d %d\n",c1,ans);
82         }
83     }
84     return 0;
85 }
View Code

posted @ 2017-05-06 10:15  江屿  阅读(239)  评论(0编辑  收藏  举报