#include #include #include using namespace atcoder; using mint = modint998244353; using namespace std; #define rep(i,n) for (int i = 0; i < (n); ++i) #define Inf32 1000000001 #define Inf64 4000000000000000001 template struct perArray{ struct node{ T value; int l=-1,r=-1; }; int sz; vector nodes; vector roots; void build(vector v,int now = -1){ if(now==-1){ sz = v.size(); nodes.push_back(node()); now = 0; roots.push_back(0); } if(v.size()==1){ nodes[now].value = v[0]; return; } vector l,r; rep(i,v.size()){ if(i>1)){ int temp = nodes[now].l; nodes[now].l = nodes.size(); nodes.push_back(nodes[temp]); set(p,ind,x,nodes.size()-1,(length>>1)); } else{ int temp = nodes[now].r; nodes[now].r = nodes.size(); nodes.push_back(nodes[temp]); set(p,ind - (length>>1),x,nodes.size()-1,(length+1)>>1); } } return ret; } T get(int p,int ind,int now = -1,int length = -1){ if(now==-1){ now = roots[p]; length = sz; } if(length==1)return nodes[now].value; if(ind<(length>>1)){ return get(p,ind,nodes[now].l,length>>1); } else{ return get(p,ind - (length>>1),nodes[now].r,(length+1)>>1); } } int size(){ return sz; } }; struct perDsu{ perArray A; vector roots; perDsu(int n){ vector t(n,-1); A.build(t); roots.push_back(0); } int merge(int p,int a,int b){ int ret = roots.size(); int La = leader(p,a); int Lb = leader(p,b); if(La==Lb)return p; if(size(p,La)> groups(int p){ vector> temp(A.size(),vector()); rep(i,A.size()){ temp[leader(p,i)].push_back(i); } vector> ret; rep(i,temp.size()){ if(temp[i].size()>0)ret.push_back(temp[i]); } return ret; } }; int main(){ int n,x0,q; cin>>n>>x0>>q; perDsu D(n); vector t(q+1),a(q+1),b(q+1),p(q+1); int x= x0; vector memo(q+1,-1); vector is(1,0); for(int i=1;i<=q;i++){ scanf("%d",&t[i]); p[i] = p[i-1]; if(t[i]==1){ scanf("%d %d",&a[i],&b[i]); //cin>>a[i]>>b[i]; p[i] = D.merge(p[i],a[i],x); is.push_back(i); } if(t[i]==2){ scanf("%d %d",&a[i],&b[i]); if(a[i]==b[i])continue; if(D.same(p[i],a[i],b[i])){ int ok = 0,ng = is.size(); while(ng-ok>1){ int mid = (ok+ng)/2; if(D.same(p[is[mid]],a[i],b[i]))ng = mid; else ok = mid; } memo[i] = b[is[ok+1]]; x += memo[i]; x %= n; } } if(t[i]==3){ scanf("%d",&a[i]); } if(t[i]==4){ scanf("%d",&a[i]); x += a[i]; x %= n; } } //cout<<'a'< A(n); for(int i=1;i<=q;i++){ if(t[i]==1){ int la = D2.leader(a[i]),lb = D2.leader(x); if(D2.same(la,lb))continue; mint tt = D2.size(a[i]); tt *= D2.size(x); tt *= b[i]; tt += A[la] + A[lb]; D2.merge(la,lb); int lc = D2.leader(la); int ld = lc^la^lb; A[ld] = 0; A[lc] = tt; } if(t[i]==2){ if(a[i]==b[i]){ printf("0\n"); continue; } printf("%d\n",memo[i]); if(memo[i]!=-1){ x += memo[i]; x %= n; } /* if(D.same(p[i],a[i],b[i])){ x += memo[i]; x %= n; printf("%d\n",memo[i]); //cout<