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

tuple<long long, long long, long long> ext_gcd(long long a, long long b) {
  if (b == 0) return {a, 1, 0};
  auto [gcd, y, x] = ext_gcd(b, a%b);
  y -= a/b * x;
  return {gcd, x, y}; // a*x + b*y = gcd
}

pair<long long,long long> crt(const vector<long long> &r, const vector<long long> &m) {
  /* return x that satisfies x = a mod b, for a in r, for b in m */
  /* O(n log lcm(m[i]))*/
  assert(r.size() == m.size());
  auto mod=[&](long long a,long long k){return (a%k+k)%k;}; // a mod k for negative a
  long long y = 0, lcm = 1; int n = r.size();
  for(int i=0; i<n; ++i) {
    assert(m[i] > 0);
    auto [g, p, q] = ext_gcd(lcm, m[i]);
    if(y % g != r[i] % g) return make_pair(0,0);
    long long s = (mod(r[i],m[i]) - y) / g * p % (m[i]/g);
    y = mod(y + lcm*s, lcm*(m[i]/g));
    lcm *= m[i] / g;
  }
  return make_pair(y, lcm); // x = y mod lcm
}

void solve() {
  int x,y,p,q; cin >> x >> y >> p >> q;
  const long long INF = 2e18;
  long long ans = INF;
  for(int a=x; a<x+y; ++a) for(int b=p; b<p+q; ++b) {
    // t = a mod (2x+2y)
    // t = b mod (p+q)
    vector<long long> r(2),m(2);
    r[0] = a, r[1] = b, m[0]=2*(x+y), m[1] = p+q;
    auto [t,lcm] = crt(r,m);
    if(lcm) ans = min(ans,t);
  }
  if (ans == INF) cout << "infinity" << endl;
  else cout << ans << endl;
}

int main() {
  int t; cin >> t;
  while(t--) solve();
}

/*
#pragma GCC optimize("O2")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("avx,avx2,sse,sse2,fma")
//*/
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef long double ld;
typedef pair<int  ,int > pii;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

const ll maxn  = 3e6;
const ll mod =1e9+7;
const ld PI = acos((ld)-1);

#define pb push_back
#define endl '\n'
#define dokme(x) cout << x , exit(0)
#define migmig ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define ms(x , y) memset(x , y , sizeof x)
ll pw(ll a, ll b, ll md = mod){ll res = 1;while(b){if(b&1){res=(a*res)%md;}a=(a*a)%md;b>>=1;}return(res);}

int n;
char aa , ab , ba , bb;

ll F[maxn];

ll f(int x){
	if(x <= 1)return(F[x] = 1);
	if(F[x])return(F[x]);
	return( F[x] = (f(x - 1) + f(x - 2))%mod );
}

int32_t main(){
    migmig;
	cin >> n >> aa >> ab >> ba >> bb;
	if(n <= 3)dokme(1);
	if(aa == ab && ab == ba && ba == bb)dokme(1);
	if(ab == 'B'){
		if(bb == 'B')dokme(1);
		if(ba == 'A')dokme(pw(2 , n - 3));
		dokme(f(n - 2));
	}
	if(aa == 'A')dokme(1);
	if(ba == 'B')dokme(pw(2 , n - 3));
	dokme((f(n - 2)));
	
    return(0);
}
