#include // #include #include using namespace std; // using namespace atcoder; using bint = boost::multiprecision::cpp_int; using ll = long long; using ull = unsigned long long; using P = pair; using vi = vector; using vvi = vector; using vvvi = vector; #define rep(i,n) for(ll i = 0;i < (ll)n;i++) #define ALL(x) (x).begin(),(x).end() #define sz(c) ((ll)(c).size()) #define LB(A,x) (int)(lower_bound(A.begin(),A.end(),x)-A.begin()) #define UB(A,x) (int)(upper_bound(A.begin(),A.end(),x)-A.begin()) // #define MOD 1000000007 #define MOD 998244353 templateusing min_priority_queue=priority_queue,greater>; templateostream&operator<<(ostream&os,vector&v){for(int i = 0;i < v.size();i++)os<istream&operator>>(istream&is,vector&v){for(T&in:v)is>>in;return is;} templateostream&operator<<(ostream&os,pair&p){os<istream&operator>>(istream&is,pair&p){is>>p.first>>p.second;return is;} class UnionFind{ public: vector par; UnionFind(long long size) : par(size,-1){} bool unite(int x,int y){ x = root(x),y = root(y); if(x == y)return false; if(par[y] < par[x])swap(x,y); par[x] += par[y]; par[y] = x; return true; } bool find(int x,int y){ return root(x) == root(y); } int root(int x){ return par[x] < 0 ? x : par[x] = root(par[x]); } int size(int x){ return -par[root(x)]; } }; const int LG_N = 20; const int MX_N = 200000; vi d(MX_N); vector> nxt(MX_N,vector(LG_N)); vector> v(MX_N); vector> cand(MX_N,vector(2)); UnionFind uf(MX_N); inline void dfs(int ov,int pre){ nxt[ov][0] = pre; rep(i,LG_N-1)nxt[ov][i+1] = nxt[nxt[ov][i]][i]; for(auto [nv,we] : v[ov]){ if(nv == pre)continue; d[nv] = d[ov] + we; dfs(nv,ov); } } ll LCA(ll a,ll b){ if(d[a] < d[b])swap(a,b); for(int i = LG_N-1;i >= 0;i--)if(d[nxt[a][i]] >= d[b])a = nxt[a][i]; if(a == b)return a; for(int i = LG_N-1;i >= 0;i--)if(nxt[a][i] != nxt[b][i])a = nxt[a][i],b = nxt[b][i]; return nxt[a][0]; } inline ll dist(ll a,ll b){ if(!uf.find(a,b))return -1; return d[a] + d[b]-2*d[LCA(a,b)]; } inline void ch(ll a,ll b){ ll mx = dist(cand[a][0],cand[a][1]); P k = {cand[a][0],cand[a][1]}; ll l = dist(cand[b][0],cand[b][1]); if(l > mx){ k = {cand[b][0],cand[b][1]}; mx = l; } rep(i,2)rep(j,2){ l = dist(cand[a][i],cand[b][j]); if(l > mx){ mx = l; k = {cand[a][i],cand[b][j]}; } } cand[b][0] = k.first; cand[b][1] = k.second; } int main(){ ios_base::sync_with_stdio(0), cin.tie(0); ll n,X,Q; cin >> n >> X >> Q; rep(i,n)rep(j,LG_N)nxt[i][j] = i; rep(i,n)rep(j,2)cand[i][j] = i; while(Q--){ ll t;cin >> t; if(t == 1){ ll a,w;cin >> a >> w; ll b = X; if(uf.size(b) < uf.size(a))swap(b,a); d[a] = d[b] + w; dfs(a,b); v[a].emplace_back(b,w); v[b].emplace_back(a,w); a = uf.root(a),b = uf.root(b); uf.unite(b,a); ch(a,b); }else if(t == 2){ ll a,b;cin >> a >> b; ll res = dist(a,b); cout << res << "\n"; if(res != -1)X = (X + res)%n; }else if(t == 3){ ll a;cin >> a; a = uf.root(a); cout << dist(cand[a][0],cand[a][1]) << "\n"; }else{ ll val;cin >> val; X = (X + val)%n; } } return 0; }