#include using namespace std; using ll = long long; struct problem_H { int MAX_LOGV, N; vector>> G; vector> parent; vector dp; vector depth; vector parent_or_size; vector> diameter; queue que; problem_H(int n) : N(n) { MAX_LOGV = __lg(N) + 1; G.resize(N); parent.resize(MAX_LOGV, vector(N, -1)); parent_or_size.resize(N, -1); dp.resize(N), depth.resize(N); diameter.resize(N); for(int i = 0; i < N; i++) diameter[i] = make_tuple(0, i, i); } int leader(int v){ return parent_or_size[v] < 0 ? v : parent_or_size[v]; } void merge(int u, int v, int w){ int x = leader(u), y = leader(v); if(-parent_or_size[x] < -parent_or_size[y]) { swap(x, y); swap(u, v); } parent_or_size[x] += parent_or_size[y]; int log_limit = __lg(-parent_or_size[x]) + 1; G[u].emplace_back(v, w); G[v].emplace_back(u, w); parent[0][v] = u; depth[v] = depth[u] + 1; dp[v] = dp[u] + w; que.push(v); while(!que.empty()){ v = que.front(); que.pop(); parent_or_size[v] = x; for(int i = 0; i + 1 < log_limit; i++){ if(parent[i][v] == -1) parent[i + 1][v] = -1; else parent[i + 1][v] = parent[i][parent[i][v]]; } for(auto &edge : G[v]){ tie(u, w) = edge; if(parent[0][v] == u) continue; que.push(u); parent[0][u] = v; depth[u] = depth[v] + 1; dp[u] = dp[v] + w; } } update_diameter(x, y); } void update_diameter(int x, int y){ tuple mx = max(diameter[x], diameter[y]); array cv; ll temp; tie(temp, cv[0], cv[1]) = diameter[x]; tie(temp, cv[2], cv[3]) = diameter[y]; for(int i = 0; i < 2; i++){ for(int j = 2; j < 4; j++){ mx = max(mx, make_tuple(dist(cv[i], cv[j]), cv[i], cv[j])); } } diameter[x] = mx; } long long dist(int u, int v){ if(leader(u) != leader(v)) return -1; if(depth[v] < depth[u]) swap(v, u); long long res = dp[u] + dp[v]; int d = depth[v] - depth[u]; for(int i = MAX_LOGV - 1; i >= 0; i--){ if(d >> i & 1) v = parent[i][v]; } if(u == v) return res - 2 * dp[v]; for(int i = MAX_LOGV - 1; i >= 0; i--){ if(parent[i][v] != parent[i][u]){ v = parent[i][v]; u = parent[i][u]; } } v = parent[0][v]; return res - 2 * dp[v]; } }; int main(){ ios::sync_with_stdio(false); cin.tie(0); int N, Q; ll X; cin >> N >> X >> Q; problem_H uf(N); int type, u, v, w; while(Q--){ cin >> type; if(type == 1){ cin >> v >> w; uf.merge(v, X, w); }else if(type == 2){ cin >> u >> v; ll d = uf.dist(u, v); cout << d << '\n'; if(d != -1) (X += d) %= N; }else if(type == 3){ cin >> v; cout << get<0>(uf.diameter[uf.leader(v)]) << '\n'; }else{ cin >> v; X += v; if(X >= N) X -= N; } } }