#include <bits/stdc++.h>

using namespace std;

const int N = 2e5 + 10;

int a[N], b[N], c[N], sum[N], n, m;

vector<int> vt[N];

inline int lowbit(int x) {
  return x & (-x);
}

void update(int x, int v) {
  while (x <= n) {
    sum[x] += v;
    x += lowbit(x);
  }
}

int query(int x) {
  int ans = 0;
  while (x) {
    ans += sum[x];
    x -= lowbit(x);
  }
  return ans;
}

int query(int l, int r) {
  return query(r) - query(l - 1);
}

int main() {
  // freopen("in.txt", "r", stdin);
  // freopen("out.txt", "w", stdout);
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    c[i] = a[i] + i;
  }
  sort(c + 1, c + 1 + n);
  m = unique(c + 1, c + 1 + n) - (c + 1);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &b[i]);
    int pos = lower_bound(c + 1, c + 1 + m, b[i] + i) - c;
    if (c[pos] != b[i] + i) {
      puts("-1");
      return 0;
    }
    b[i] = pos;
  }
  for (int i = n; i >= 1; i--) {
    vt[lower_bound(c + 1, c + 1 + m, a[i] + i) - c].push_back(i);
  }
  long long ans = 0;
  for (int i = 1; i <= n; i++) {
    if (!vt[b[i]].size()) {
      puts("-1");
      return 0;
    }
    int cur = vt[b[i]].back();
    ans += cur + query(cur + 1, n) - i;
    vt[b[i]].pop_back();
    update(cur, 1);
  }
  printf("%lld\n", ans);
  return 0;
}
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define MOD int(1e9+7)
#define INF int(1e9+7)
#define LINF ll(1e18+7)
#define PI acos(-1)
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define P pair<ll,ll>
#define chmax(x,y) (x = max(x,y))
#define chmin(x,y) (x = min(x,y))

ll ext_gcd(ll a, ll b, ll &x, ll &y){
  if(b==0){
    x=1;
    y=0;
    return a;
  }
  ll d=ext_gcd(b,a%b,y,x);
  y -= a/b*x;
  return d;
}

P crt(const vector<ll> &b, const vector<ll> &m){
  ll r=0,M=1;
  rep(i,(int)b.size()){
    ll p,q;
    ll d = ext_gcd(M,m[i],p,q);
    if((b[i]-r)%d != 0) return P(0,-1);
    ll tmp = (b[i]-r)/d * p %(m[i]/d);
    r += M * tmp;
    M *= m[i]/d;
  }
  return P((r+M)%M,M);
}

int main(){
  int t; cin>>t;
  ll x,y,p,q;
  rep(i,t){
    ll ans=LLONG_MAX;
    cin>>x>>y>>p>>q;
    for(ll t1=x; t1<x+y; t1++){
      for(ll t2=p; t2<p+q; t2++){
        ll r,mod;
        vector<ll> b(2),m(2);
        b[0]=t1; b[1]=t2;
        m[0]=2*x+2*y; m[1]=p+q;
        tie(r,mod)=crt(b,m);
        if(mod!=-1) chmin(ans,r);
      }
    }
    if(ans==LLONG_MAX) cout<<"infinity"<<endl;
    else cout<<ans<<endl;
  }
}