#include #include #include #include #include using namespace std ; typedef long long LL ; #define clr( a , x ) memset ( a , x , sizeof a ) #define ls ( o << 1 ) #define rs ( o << 1 | 1 ) #define root 1 , 1 , n #define lson ls , l , mid #define rson rs , mid + 1 , r const int MAXN = 100005 ; const int MAXE = 200005 ; const LL INF = 1e18 ; const int mod = 998244353 ; int minv[MAXN << 2] ; int zero[MAXN << 2] ; int b[MAXN] , c[MAXN] ; int a[MAXN] ; void solve () { int n , ok = 1 ; scanf ( "%d" , &n ) ; b[0] = n + 1 ; for ( int i = 1 ; i <= n ; ++ i ) { scanf ( "%d" , &b[i] ) ; if ( b[i] > b[i - 1] ) ok = 0 ; } c[0] = 0 ; for ( int i = 1 ; i <= n ; ++ i ) { scanf ( "%d" , &c[i] ) ; if ( c[i] < c[i - 1] ) ok = 0 ; } if ( b[1] != c[1] ) ok = 0 ; if ( !ok ) { printf ( "0\n" ) ; return ; } a[1] = b[1] ; int cnt = 0 , ans = 1 ; for ( int i = 2 ; i <= n ; ++ i ) { if ( b[i] == b[i - 1] ) { if ( c[i] == c[i - 1] ) { ans = 1LL * ans * cnt % mod ; cnt -- ; if ( cnt < 0 ) ok = 0 ; } else { cnt += c[i] - c[i - 1] - 1 ; } } else { if ( c[i] == c[i - 1] ) { cnt += b[i - 1] - b[i] - 1 ; } else { ok = 0 ; ans = 0 ; break ; } } } if ( !ok ) printf ( "0\n" ) ; else printf ( "%d\n" , ans ) ; } int main () { int T ; scanf ( "%d" , &T ) ; getchar () ; for ( int i = 1 ; i <= T ; ++ i ) { solve () ; } return 0 ; }