#include #include #include using namespace std; typedef vector VI; int N, M; int root = 1; VI V[100002]; bool S[100002]; int RMQ[20][200002]; int Niv[200002], Is[200002], Enter[200002], sizeE; int Lg[200002]; void makeE(int x, int level) { S[x] = true; Enter[x] = ++sizeE; Niv[sizeE] = level; Is[sizeE] = x; for (VI::iterator it = V[x].begin(); it != V[x].end(); ++it) if (!S[*it]) { makeE(*it, level + 1); Niv[++sizeE] = level; Is[sizeE] = x; } } int LCA(int nod1, int nod2) { if (Enter[nod1] > Enter[nod2]) swap(nod1, nod2); int k = Lg[Enter[nod2] - Enter[nod1] + 1]; if (Niv[RMQ[k][Enter[nod1]]] < Niv[RMQ[k][Enter[nod2] - (1 << k) + 1]]) return Is[RMQ[k][Enter[nod1]]]; else return Is[RMQ[k][Enter[nod2] - (1 << k) + 1]]; } int main() { for (int i = 2; i <= 200000; ++i) Lg[i] = Lg[i >> 1] + 1; cin >> N >> M; for (int i = 2, nod1, nod2; i <= N; ++i) { cin >> nod1 >> nod2; V[nod1].push_back(nod2); V[nod2].push_back(nod1); } makeE(1, 0); for (int i = 1; i <= sizeE; ++i) RMQ[0][i] = i; for (int s = 1; (1 << s) <= sizeE; ++s) for (int i = 1; i <= sizeE; ++i) { RMQ[s][i] = RMQ[s - 1][i]; if (i + (1 << (s - 1)) <= sizeE && Niv[RMQ[s - 1][i + (1 << (s - 1))]] < Niv[RMQ[s][i]]) RMQ[s][i] = RMQ[s - 1][i + (1 << (s - 1))]; } for (int i = 1, type; i <= M; ++i) { cin >> type; if (type == 1) { int nod; cin >> nod; root = nod; } else { int nod1, nod2; cin >> nod1 >> nod2; int now = LCA(nod1, nod2); if (now == nod1 || now == nod2) { if (Niv[Enter[nod1]] < Niv[Enter[nod2]]) swap(nod1, nod2); if (Niv[Enter[LCA(nod1, root)]] < Niv[Enter[nod1]] && Niv[Enter[LCA(nod1, root)]] > Niv[Enter[nod2]]) cout << LCA(nod1, root) << '\n'; else cout << -1 << '\n'; } else { if (Niv[Enter[LCA(nod1, root)]] >= Niv[Enter[nod1]] && Niv[Enter[LCA(nod2, root)]] >= Niv[Enter[nod2]]) cout << -1 << '\n'; else { if (Niv[Enter[LCA(nod1, root)]] <= Niv[Enter[now]] && Niv[Enter[LCA(nod2, root)]] <= Niv[Enter[now]]) cout << now << '\n'; else if (LCA(root, nod1) == now) cout << LCA(root, nod2) << '\n'; else cout << LCA(root, nod1) << '\n'; } } } } }