#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>

#define int long long

using namespace std;

const int MOD = 998244353;

int n;
vector<int> a;

vector<int> mem;

int g(int x) {
    if (mem[x] != -1) return mem[x];
    if (x == 0) return mem[x] = 0;
    return mem[x] = (3 * g(x - 1) + 2) % MOD;
}


int f(int x, int pos) {
    if (x == 0) return 0;
    if (a[x - 1] == pos) {
        return f(x - 1, pos);
    } else if (a[x - 1] == 1) {
        return (g(x - 1) + 1 + f(x - 1, 2 - pos)) % MOD;
    } else {
        return (2 * g(x - 1) + 2 + f(x - 1, pos)) % MOD;
    }
}

void solve() {
    cin >> n;
    a.resize(n);
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
        a[i]--;
    }
    mem.assign(n + 1, -1);

    int ans1 = f(n, 0);

    auto c = a;
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
        a[i]--;
    }
    int ans2 = f(n, 0);
    reverse(c.begin(), c.end());
    reverse(a.begin(), a.end());

    int i = 0;
    while (i < n && c[i] == 2 && a[i] == 2) {
        i++;
    }
    if (i == n) {
        cout << 0 << endl;
        return;
    }
    if (c[i] < a[i]) {
        cout << (ans2 - ans1 + MOD) % MOD << endl;
        return;
    } else if (c[i] > a[i]) {
        cout << (ans1 - ans2 + MOD) % MOD << endl;
        return;
    } else {
        bool suck = (c[i] > 0);
        for (int j = i + 1; j < n; ++j) {
            if (c[j] > a[j]) {
                if (!suck) {
                    cout << (ans1 - ans2 + MOD) % MOD << endl;
                    return;
                } else {
                    cout << (ans2 - ans1 + MOD) % MOD << endl;
                    return;
                }
            }
            if (c[j] < a[j]) {
                if (!suck) {
                    cout << (ans2 - ans1 + MOD) % MOD << endl;
                    return;
                } else {
                    cout << (ans1 - ans2 + MOD) % MOD << endl;
                    return;
                }
            }
            suck ^= (c[j] > 0);
        }
    }
    cout << 0 << endl;
}

signed main() {
    cin.tie(nullptr)->sync_with_stdio(false);
    int t = 1;
    cin >> t;
    while (t--) {
        solve();
    }
}