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
| #include <cstdio>
#include <cctype>
#include <vector>
using namespace std;
namespace fast_io {
inline char read() {
static const int IN_LEN = 1000000;
static char buf[IN_LEN], *s, *t;
return s==t?(((t=(s=buf)+fread(buf,1,IN_LEN,stdin))== s)?-1:*s++) : *s++;
}
inline void read(int &x) {
static bool iosig;
static char c;
for (iosig = false, c = read(); !isdigit(c); c = read()) {
if (c == '-') iosig = true;
if (c == -1) return;
}
for (x = 0; isdigit(c); c = read())
x = ((x+(x<<2))<<1) + (c ^ '0');
if (iosig) x = -x;
}
const int OUT_LEN = 1000000;char obuf[OUT_LEN], *ooh = obuf;
inline void print(char c) {
if (ooh == obuf + OUT_LEN) fwrite(obuf, 1, OUT_LEN, stdout), ooh = obuf;
*ooh++ = c;
}
inline void print(int x) {
static int buf[30], cnt;
if (x == 0)
print('0');
else {
if (x < 0) print('-'), x = -x;
for (cnt = 0; x; x /= 10) buf[++cnt] = x % 10 + 48;
while (cnt) print((char)buf[cnt--]);
}
}
inline void flush() {
fwrite(obuf, 1, ooh - obuf, stdout);
}
}using namespace fast_io;
const int MAXN = 510000;
vector<int> edge[MAXN];
int n,m;
int dep[MAXN],siz[MAXN],fa[MAXN],son[MAXN],top[MAXN],id[MAXN],cnt = 1;
//添加从a到b的无向边
void addedge(int a,int b){
edge[a].push_back(b);
edge[b].push_back(a);
}
//树链剖分的第一个dfs
void dfs1(int nown,int f,int depth){
siz[nown] = 1,fa[nown] = f,dep[nown] = depth;
int maxsum = -1;son[nown] = 0;
for(int i = 0;i<edge[nown].size();i++){
int to = edge[nown][i];
if(to == f) continue;
dfs1(to,nown,depth+1);
if(siz[to] > maxsum) maxsum = siz[to],son[nown] = to;
siz[nown] += siz[to];
}
}
//树链剖分的第二个dfs
void dfs2(int nown,int topf){
id[nown] = cnt++;top[nown] = topf;
if(son[nown] == 0) return;
dfs2(son[nown],topf);
for(int i = 0;i<edge[nown].size();i++){
int to = edge[nown][i];
if(to == fa[nown]|| to == son[nown]) continue;
dfs2(to,to);
}
}
//求a,b两点的LCA
int lca(int a,int b){
while(top[a]!=top[b]){
if(dep[top[a]] < dep[top[b]]) swap(a,b);
a = fa[top[a]];
}
if(dep[a] < dep[b]) swap(a,b);
return b;
}
//初始化以及dfs
void init(){
read(n),read(m);
int a,b;
for(int i = 1;i<=n-1;i++){
read(a),read(b);
addedge(a,b);
}
dfs1(1,0,1);
dfs2(1,1);
}
//回应询问
void solve(){
int a,b,c,a1,b1,c1,ans,dis;
for(int i = 1;i<=m;i++){
read(a),read(b),read(c);
//a1,b1,c1的意义见下
a1 = lca(a,b),b1 = lca(b,c),c1 = lca(c,a);
dis = 0;
if(a1 == b1)
ans = c1;
else if(b1 == c1)
ans = a1;
else if(c1 == a1)
ans = b1;
//计算dis的公式
dis = dep[a] + dep[b] + dep[c] - dep[a1] - dep[b1] - dep[c1];
print(ans),print(' '),print(dis),print('\n');
}
}
int main(){
init();
solve();
flush();
return 0;
}
|