1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
| #include<bits/stdc++.h> using namespace std;
const int MAXN=500000*2+5; int n,m;
struct tu{ private: struct ed{ int to,nex; } e[MAXN]; int head[MAXN],newp,siz,root,H,f[MAXN][20]; int depth[MAXN]; bool bfsed; public: inline void clear(void){ memset(e,0,sizeof(e)); memset(head,0,sizeof(head)); memset(f,0,sizeof(f)); memset(depth,0,sizeof(depth)); newp=0; siz=0; root=1; bfsed=0; } inline void vAdd(int p1,int p2){ ++newp; e[newp].to=p2; e[newp].nex=head[p1]; head[p1]=newp; } inline void resize(int s){ siz=s; H=(int)(1.0*log(siz)/log(2)+0.5); } inline int size(void){ return siz; } inline int lca(int p1,int p2){ if(!bfsed){ bfs(); } if(depth[p1]<depth[p2]){ swap(p1,p2); } for(int i=H;i>=0;--i){ if(depth[f[p1][i]]>=depth[p2]){ p1=f[p1][i]; } } if(p1==p2)return p1; for(int i=H;i>=0;--i){ if(f[p1][i]!=f[p2][i]){ p1=f[p1][i]; p2=f[p2][i]; } } return f[p1][0]; } inline void solve(int x,int y,int z){ int a,b,c; a=lca(x,y); b=lca(y,z); c=lca(x,z); int ans1,ans2; if(depth[a]>=depth[b] && depth[a]>=depth[c]){ ans1=a; } else if(depth[b]>=depth[a] && depth[b]>=depth[c]){ ans1=b; } else if(depth[c]>=depth[a] && depth[c]>=depth[b]){ ans1=c; } int pt1=depth[x]-depth[a]; int pt2=depth[y]-depth[b]; int pt3=depth[z]-depth[c]; ans2=pt1+pt2+pt3; printf("%d %d\n",ans1,ans2); } inline void bfs(void){ queue<int> q; q.push(root); depth[root]=1; while(!q.empty()){ int x=q.front(); q.pop(); for(int i=head[x];i;i=e[i].nex){ int y=e[i].to; if(depth[y])continue; depth[y]=depth[x]+1; f[y][0]=x; for(int j=1;j<=H;++j){ f[y][j]=f[f[y][j-1]][j-1]; } q.push(y); } } bfsed=1; } };
tu a;
int main(void){ scanf("%d%d",&n,&m); a.clear(); a.resize(n); for(int i=1;i<n;++i){ int p1,p2; scanf("%d%d",&p1,&p2); a.vAdd(p1,p2); a.vAdd(p2,p1); } for(int i=1;i<=m;++i){ int keke,kaka,waiwai; scanf("%d%d%d",&keke,&kaka,&waiwai); a.solve(keke,kaka,waiwai); } return 0; }
|