BZOJ1787 [Ahoi2008]Meet 紧急集合[结论题]

location。

求到树上三点距离和最短的点及此距离。


这个不还是分类讨论题么,分两类大情况,如下图。

于是乎发现三个点对的lca中较深的那个lca是答案点。距离就是两两点对距离加起来除以2即可。这个通过画图真的很好理解。毫无技术含量。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<cmath>
 6 #define dbg(x) cerr << #x << " = " << x <<endl
 7 using namespace std;
 8 typedef long long ll;
 9 typedef double db;
10 typedef pair<int,int> pii;
11 template<typename T>inline T _min(T A,T B){return A<B?A:B;}
12 template<typename T>inline T _min(T A,T B,T C){return _min(A,_min(B,C));}
13 template<typename T>inline T _max(T A,T B){return A>B?A:B;}
14 template<typename T>inline char MIN(T&A,T B){return A>B?(A=B,1):0;}
15 template<typename T>inline char MAX(T&A,T B){return A<B?(A=B,1):0;}
16 template<typename T>inline void _swap(T&A,T&B){A^=B^=A^=B;}
17 template<typename T>inline T read(T&x){
18     x=0;int f=0;char c;while(!isdigit(c=getchar()))if(c=='-')f=1;
19     while(isdigit(c))x=x*10+(c&15),c=getchar();return f?x=-x:x;
20 }
21 const int N=5e5+7;
22 int n,q;
23 struct thxorz{
24     int to,nxt;
25 }G[N<<1];
26 int Head[N],tot;
27 inline void Addedge(int x,int y){
28     G[++tot].to=y,G[tot].nxt=Head[x],Head[x]=tot;
29     G[++tot].to=x,G[tot].nxt=Head[y],Head[y]=tot;
30 }
31 int depth[N],son[N],siz[N],fa[N],topfa[N];
32 #define y G[j].to
33 void dfs1(int x,int fat){
34     int res=-1;fa[x]=fat;siz[x]=1;
35     for(register int j=Head[x];j;j=G[j].nxt)if(y^fat){
36         depth[y]=depth[x]+1;dfs1(y,x);siz[x]+=siz[y];
37         if(MAX(res,siz[y]))son[x]=y;
38     }
39 }
40 void dfs2(int x,int topf){
41     topfa[x]=topf;
42     if(!son[x])return;
43     dfs2(son[x],topf);
44     for(register int j=Head[x];j;j=G[j].nxt)if((y^fa[x])&&(y^son[x]))dfs2(y,y);
45 }
46 #undef y
47 inline int LCA(int x,int y){
48     while(topfa[x]^topfa[y]){
49         if(depth[topfa[x]]<depth[topfa[y]])_swap(x,y);
50         x=fa[topfa[x]];
51     }
52     return depth[y]<depth[x]?y:x;
53 }
54 inline void Query(int x,int y,int z){
55     int lca1=LCA(x,y),lca2=LCA(x,z),lca3=LCA(y,z);//dbg(lca1),dbg(lca2),dbg(lca3);
56     int minx=lca1;
57     if(depth[minx]<depth[lca2])minx=lca2;
58     if(depth[minx]<depth[lca3])minx=lca3;
59     int STOstostostoTHXorzorzorzORZ=(depth[x]+depth[y]-2*depth[lca1]+depth[x]+depth[z]-2*depth[lca2]+depth[z]+depth[y]-2*depth[lca3])>>1;
60     printf("%d %d\n",minx,STOstostostoTHXorzorzorzORZ);
61 }
62 int x,y,z;
63 int main(){//freopen("test.in","r",stdin);//freopen("test.out","w",stdout);
64     read(n);read(q);for(register int i=1;i<n;++i)read(x),read(y),Addedge(x,y);
65     depth[1]=1,dfs1(1,0);dfs2(1,1);
66     while(q--)read(x),read(y),read(z),Query(x,y,z);
67     return 0;
68 }
上一篇:re模块


下一篇:「CF319E」Ping-Pong「线段树」「并查集」