#include #include #include #include using namespace std; int roots[10001]; int n, m, t, x, y; int indexRoot; int memory[10001][10001]; bool alreadyFound[10001]; void read(){ cin >> n >> m; int a, b; for(int i = 0; i < n-1; i++){ cin >> a >> b; if (b < a) roots[a] = b; else roots[b] = a; } memcpy(memory[1], roots, n*sizeof(int)); alreadyFound[1] = true; } deque getPath(int index){ deque v; v.push_front(index); while (index){ v.push_front(roots[index]); index = roots[index]; } v.pop_front();//this shouldn't matter return v; } void change(int index, int ancestor, bool recCall){ if(alreadyFound[index] && !recCall) { memcpy(memory[index], roots, n*sizeof(int)); } else { alreadyFound[index] = true; int oldAncestor = roots[index]; roots[index] = ancestor; if(oldAncestor != 0){ change(oldAncestor, index, true); } } } int getLCA(deque dq1, deque dq2){ int index = 0; while(dq1.front() == dq2.front()){ index = dq1.front(); dq1.pop_front(); dq2.pop_front(); } return index; } void conflict(int a, int b){ int boss = getLCA(getPath(a), getPath(b)); if(boss == a || boss == b) cout << -1 << "\n"; else cout << boss << "\n"; } int main() { read(); for(int i = 0; i < m; i++){ cin >> t >> x; if(t == 1){ indexRoot = x; } else{ cin >> y; change(indexRoot,0, false); conflict(x, y); } } }