RT,写的树剖,写错了但是100pts导致另一题调了一年
#include<bits/stdc++.h>
using namespace std;
int n, m, u, v, e, h[1000005], ne[1000005], t[1000005], w[1000005], ww, d[1000005], c[1000005], siz[1000005], z[1000005], f[1000005], dfn[1000005], ff[1000005], k, s;
int ct (int x, int y, int z) {
e++;
ne[e] = h[x];
h[x] = e;
t[e] = y;
w[e] = z;
return 0;
}
int dfs(int x) {
siz[x] = 1;
for (int i = h[x]; i; i = ne[i]) {
if (t[i] != f[x]) {
f[t[i]] = x;
d[t[i]] = d[x] + 1;
dfs(t[i]);
if (siz[z[x]] < siz[t[i]]) z[x] = t[i];
siz[x] += siz[t[i]];
}
}
return 0;
}
int dfss(int x) {
dfn[x] = ++dfn[0];
for (int i = h[x]; i; i = ne[i]) {
if (t[i] == z[x]) {
ff[t[i]] = ff[x];
dfss(t[i]);
}
}
for (int i = h[x]; i; i = ne[i]) {
if (t[i] != f[x] && t[i] != z[x]) {
ff[t[i]] = t[i];
dfss(t[i]);
}
}
return 0;
}
int CC (int x, int y) {
while(ff[x] != ff[y]) {
if (d[ff[x]] >= d[ff[y]]) {
x = ff[x];
if (x != s)
x = f[x];
} else {
y = ff[y];
if (y != s)
y = f[y];
}
}
if (x == y)
return y;
else {
if (d[x] < d[y]) return x;
return y;
}
}
int main () {
// cin >> n;
cin >> n >> k >> s;
for (int i = 1; i < n; i++) {
cin >> u >> v;
ct(u, v, i);
ct(v, u, i);
}
d[s] = 1;
ff[s] = s;
dfs(s);
dfss(s);
// for (int i = 1; i <= n; i++) {cout << d[i] << " ";
// }
// cout << "\n";
for (int i = 1; i <= k; i++) {
cin >> u >> v;
cout << CC (u, v) << "\n";
}
// cin >> k;
// for (int i = 1; i <= k; i++) {
// cin >> u >> v;
// anss = CC (u, v);
// ans[u]++;
// ans[v]++;
// ans[anss]--;
// ans[anss]--;
// }
// dfss(1);
// for (int i = 1; i < n; i++) cout << abs(cnt[i])<< " ";
}