第三次了。。。
#include <bits/stdc++.h>
using namespace std;
int n, m, k;
int f[100005][16], dep[100005];
int ans[100005];
vector <int> G[100005];
queue <pair <int, int> > q;
set <int> s1, s2;
struct Query {int x, y;}a[100005];
void dfs (int u) {
for (int i = 1; i <= 15; i ++) f[u][i] = f[f[u][i - 1] ][i - 1];
for (int v : G[u]) {
if (v == f[u][0]) continue;
f[v][0] = u;
dep[v] = dep[u] + 1;
dfs (v);
}
}
int lca (int x, int y) {
if (dep[x] < dep[y]) swap (x, y);
for (int i = 15; i >= 0; i --) if (dep[f[x][i] ] >= dep[y]) x = f[x][i];
if (x == y) return x;
for (int i = 15; i >= 0; i --) if (f[x][i] != f[y][i]) {
x = f[x][i];
y = f[y][i];
}
return f[x][0];
}
int dis (int x, int y) {return dep[x] + dep[y] - 2 * dep[lca (x, y)];}
int main () {
dep[1] = 1;
cin >> n;
for (int i = 1; i < n; i ++) {
int u, v;
cin >> u >> v;
G[u].push_back (v);
G[v].push_back (u);
}
dfs (1);
cin >> m;
for (int i = 1; i <= m; i ++) cin >> a[i].x >> a[i].y;
for (int i = 1; i <= m; i += 300) {
s1.clear ();
s2.clear ();
k = 0;
for (int j = 1; j <= n; j ++) ans[j] = 1000000000;
for (int j = 1; j < i; j ++) if (a[j].x == 0) {
if (s1.find (a[j].y) != s1.end () ) s1.erase (a[j].y);
else s1.insert (a[j].y);
}
for (int it : s1) {
q.push (make_pair (it, 0) );
ans[it] = 0;
}
while (!q.empty () ) {
int u = q.front ().first, dis = q.front ().second;
q.pop ();
for (int v : G[u]) {
if (ans[v] != 1000000000) continue;
ans[v] = dis + 1;
q.push (make_pair (v, ans[v]) );
}
}
for (int j = i; j < i + 300 && j <= m; j ++) {
if (a[j].x == 0) {
if (s2.find (a[j].y) != s2.end () ) s2.erase (a[j].y);
else s2.insert (a[j].y);
}
else {
for (int it : s2)
ans[a[j].y] = min (ans[a[j].y], dis (a[j].y, it) );
cout << (ans[a[j].y] == 1000000000 ? -1 : ans[a[j].y])<< "\n";
}
}
}
return 0;
}