#include #include #include #define i64 long long #define MOD 998244353 #define N_MAX 100000 int T, n, m, i, l, r, x, a[N_MAX + 1], b[N_MAX + 1], c[N_MAX + 1]; i64 f[N_MAX + 1] = {1}, g[N_MAX + 1] = {1}, ans; inline i64 pow(i64 a, int k) { register i64 w = 1; for (a %= MOD; k; a = a * a % MOD, k >>= 1) if (k & 1) w = w * a % MOD; return w; } inline i64 inv(i64 a) { return pow(a, MOD - 2); } int main() { for (i = 1; i <= N_MAX; ++i) f[i] = f[i - 1] * i % MOD, g[i] = g[i - 1] * inv(i) % MOD; scanf("%d", &T); while (T--) { memset(a + 1, 0, n * sizeof (int)); scanf("%d", &n); for (i = 1; i <= n; ++i) scanf("%d", &b[i]); for (i = 1; i <= n; ++i) scanf("%d", &c[i]); if (b[1] != c[1]) goto no; for (i = 2; i <= n; ++i) if (b[i] > b[i - 1] || c[i] < c[i - 1]) goto no; for (i = 1; i <= n; ++i) if (b[i] != b[i - 1]) a[i] = b[i]; for (i = 1; i <= n; ++i) if (c[i] == c[i - 1]) continue; else if (!a[i]) a[i] = c[i]; else if (a[i] != c[i]) goto no; ans = 1, m = 0; l = b[1], r = c[1]; x = r - l; for (i = 2; i <= n; ++i) { if (a[i]) { if (x < m) goto no; else ans = ans * f[x] % MOD * g[x - m] % MOD, x -= m, m = 0; x += l - b[i] + c[i] - r - 1, l = b[i], r = c[i]; } else ++m; } if (x != m) goto no; else ans = ans * f[x] % MOD; printf("%d\n", (int) ans); continue; no: puts("0"); } return 0; }