// ※※※ 解答不能 ※※※
// yutaka1999氏.
// https://atcoder.jp/contests/code-festival-2017-qualc/submissions/1704201
#include <bits/stdc++.h>
using namespace std;
#define SIZE 415
#define MOD 1000000007
typedef long long int ll;
typedef pair <int, int> P;

int dp[2][SIZE][SIZE];
int now[SIZE][SIZE];
int A[SIZE], B[SIZE];
int pa[SIZE];
int pb[SIZE];

int main(){
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; i++){
        scanf("%d", &A[i]);
        A[i]--;
        pa[A[i]] = i;
    }
    for(int i = 0; i < n; i++){
        scanf("%d", &B[i]);
        B[i]--;
        pb[B[i]] = i;
    }
    if(A[0] == B[0]){
        puts("0");
        return 0;
    }
    A[n] = n, B[n] = n;
    pa[n] = pb[n] = n + 1;
    int pos = 0;
    memset(dp, 0, sizeof(dp));
    dp[pos][1][1] = 1;
    for(int i = 1; i <= n; i++){
        pos ^= 1;
        memset(dp[pos], 0, sizeof(dp[pos]));
        for(int j = 1; j <= n + 1; j++){
            for(int k = 0; k <= n / 3; k++) now[j][k] = 0;
        }
        for(int j = 1;j <= n; j++){
            for(int k = 0; k <= n / 3; k++){
                int vl = dp[pos^1][j][k];
                if(vl == 0) continue;
                // A[i] を使わないとき
                if(pb[A[i]] < j){
                    // Bに入ってる
                    dp[pos][j][k] += vl;
                    if(dp[pos][j][k] >= MOD) dp[pos][j][k] -= MOD;
                }else if(k > 0){
                    // Cに入れる
                    dp[pos][j][k - 1] += (int)((ll)vl * (ll)k % MOD);
                    if(dp[pos][j][k - 1] >= MOD) dp[pos][j][k - 1] -= MOD;
                }
                // A[i]を使うとき
                if(pb[A[i]] >= j){
                    now[j][k] += vl;
                    if(now[j][k] >= MOD) now[j][k] -= MOD;
                }
            }
        }
        for(int j = 1; j <= n; j++){
            if(A[i] < n && B[j] == A[i]) continue;
            for(int k = 0;k <= n / 3; k++){
                int vl = now[j][k];
                if(vl == 0) continue;
                // B[j] を使わない
                if(pa[B[j]] <= i){
                    now[j + 1][k] += vl;
                    if(now[j + 1][k] >= MOD) now[j + 1][k] -= MOD;
                }else if(k > 0){
                    now[j + 1][k - 1] += (int)((ll)vl * (ll)k % MOD);
                    if(now[j + 1][k - 1] >= MOD) now[j + 1][k - 1] -= MOD;
                }
                //B[j] を使う
                if(pa[B[j]] > i){
                    dp[pos][j + 1][k + 1] += vl;
                    if(dp[pos][j + 1][k + 1] >= MOD) dp[pos][j + 1][k + 1] -= MOD;
                }
            }
        }
    }
    ll ret = dp[pos][n + 1][1];
    for(int i = 0; i < n / 3; i++){
        ret *= (ll)(3 * i + 1);
        ret %= MOD;
        ret *= (ll)(3 * i + 2);
        ret %= MOD;
    }
    printf("%lld\n", ret);
    return 0;
}