#include<cstdio>
using namespace std;
typedef long long LL;
const int maxn=400+2;
const int mod=1e9+7;
int n;
int a[maxn],b[maxn],posa[maxn],posb[maxn];
int t[maxn][maxn];
LL dp[maxn][maxn][maxn];
void DP(){
	dp[0][0][0]=1;
	for (int k=1;k<=n/3;k++)
		for (int i=1;i<=n;i++)
			for (int j=1;j<=n;j++){
				dp[k][i][j]=(dp[k][i-1][j]+dp[k][i][j-1]-dp[k][i-1][j-1]+mod)%mod;
				if (i<posa[b[j]]&&j<posb[a[i]]) dp[k][i][j]=(dp[k][i][j]+dp[k-1][i-1][j-1]*(3*k-t[i][j]))%mod;
			}
}
int main(){
	scanf("%d",&n);
	for (int i=1;i<=n;i++){
		scanf("%d",&a[i]);
		posa[a[i]]=i;
	}
	for (int i=1;i<=n;i++){
		scanf("%d",&b[i]);
		posb[b[i]]=i;
	}
	for (int i=0;i<=n;i++)
		for (int j=0;j<=n;j++)
			for (int k=1;k<=n;k++)
				if (posa[k]<=i||posb[k]<=j) t[i][j]++;
	DP();
	LL ans=dp[n/3][n][n];
	for (int i=1;i<=n;i++)
		if (i%3) ans=(ans*i)%mod;
	printf("%lld",ans);
	return 0;
}