#include namespace { #pragma GCC diagnostic ignored "-Wunused-function" #include #pragma GCC diagnostic warning "-Wunused-function" using namespace std; using namespace atcoder; #define rep(i,n) for(int i = 0; i < (int)(n); i++) #define rrep(i,n) for(int i = (int)(n) - 1; i >= 0; i--) #define all(x) begin(x), end(x) #define rall(x) rbegin(x), rend(x) template bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; } else return false; } template bool chmin(T& a, const T& b) { if (b < a) { a = b; return true; } else return false; } using ll = long long; using P = pair; using VI = vector; using VVI = vector; using VL = vector; using VVL = vector; struct Node { int depth, parent, jump; }; struct Diam { int u, v; ll d; friend bool operator<(const Diam& lhs, const Diam& rhs) { return lhs.d < rhs.d; } }; } int main() { ios::sync_with_stdio(false); cin.tie(0); int n, x, q; cin >> n >> x >> q; vector>> g(n); VL ws(n); vector nodes(n); rep(i, n) nodes[i] = {0, i, i}; vector diam(n); rep(i, n) diam[i] = {i, i, 0}; dsu uf(n); auto dist = [&](int u, int v) { ll res = ws[u] + ws[v]; if (nodes[u].depth < nodes[v].depth) swap(u, v); while (nodes[u].depth != nodes[v].depth) { int uj = nodes[u].jump; if (nodes[uj].depth >= nodes[v].depth) u = uj; else u = nodes[u].parent; } while (u != v) { int uj = nodes[u].jump, vj = nodes[v].jump; if (uj != vj) u = uj, v = vj; else u = nodes[u].parent, v = nodes[v].parent; } res -= 2 * ws[u]; return res; }; while (q--) { int type; cin >> type; if (type == 1) { int v, w; cin >> v >> w; int u = x; if (uf.size(u) > uf.size(v)) swap(u, v); int lu = uf.leader(u), lv = uf.leader(v); int l = uf.merge(u, v); auto dfs = [&](auto&& self, int u, int p, ll w_now) -> void { int pj = nodes[p].jump, pjj = nodes[pj].jump; nodes[u] = { nodes[p].depth + 1, p, nodes[p].depth + nodes[pjj].depth == 2 * nodes[pj].depth ? pjj : p }; ws[u] = w_now; for (auto [vi, wi] : g[u]) if (vi != p) self(self, vi, u, w_now + wi); }; dfs(dfs, u, v, w + ws[v]); g[u].emplace_back(v, w); g[v].emplace_back(u, w); Diam d = max(diam[lu], diam[lv]); for (int u : {diam[lu].u, diam[lu].v}) { for (int v : {diam[lv].u, diam[lv].v}) { chmax(d, Diam{u, v, dist(u, v)}); } } diam[l] = d; } else if (type == 2) { int u, v; cin >> u >> v; if (!uf.same(u, v)) { cout << -1 << '\n'; } else { ll ans = dist(u, v); cout << ans << '\n'; x = (x + ans) % n; } } else if (type == 3) { int v; cin >> v; cout << diam[uf.leader(v)].d << '\n'; } else { int value; cin >> value; x = (x + value) % n; } } }