#include <bits/stdc++.h>
using namespace std;

long long int modinv(long long int a, long long int m) {
  long long int b = m, u = 1, v = 0;
  while (b) {
    long long int t = a / b;
    a -= t * b; swap(a, b);
    u -= t * v; swap(u, v);
  }
  u %= m; 
  if (u < 0) u += m;
  return u;
}

int main() {
  int T;
  cin >> T;
  for (int i = 0; i < T; i++) {
    long long int N, S, K;
    cin >> N >> S >> K;
    long long int G = __gcd(K, N);
    if ((N - S) % G != 0) cout << -1 << endl;
    else {
      long long int A, B, n;
      A = K / G;
      B = (N - S) / G;
      n = N / G;
      long long int C = modinv(A, n);
      long long int ans = C * B % n;
      if (ans < 0) ans += n;
      cout << ans << endl;
    }
  }
}
#include<bits/stdc++.h>
typedef long long ll;
typedef unsigned long long ull;
#define int ll
#define pii pair<int,int>
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define rrep(i,a,b) for(int i=(a);i>=(b);--i)
using namespace std;
const double pi=acos(-1.0);
const double eps=1e-8;
const int INF=0x3f3f3f3f;
const int MAXN=4e5+10;
const int mod=1e9+7;
void solve()
{
    int n,q;
    string s;
    cin>>n;
    cin>>s;
    cin>>q;
    int flag=0;
    while(q--)
    {
        int t,a,b;
        cin>>t>>a>>b;
        if(t==2)
        {
            flag^=1;
        }
        else
        {
            if(flag==0)
            {
                swap(s[a-1],s[b-1]);
            }
            else
            {
                if(a<=n)
                {
                    a+=n;
                }
                else
                {
                    a-=n;
                }
                if(b<=n)
                {
                    b+=n;
                }
                else
                {
                    b-=n;
                }
                swap(s[a-1],s[b-1]);
            }
        }
    }
    if(flag)
    {
        for(int i=n;i<2*n;++i) cout<<s[i];
        for(int i=0;i<n;++i) cout<<s[i];
    }
    else
    {
        cout<<s;
    }
}
signed main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int _=1;
    //cin>>_;
    for(int i=1; i<=_; ++i)
    {
        solve();
    }
    return 0;
}



