Problem:
Score : 1200 points

Problem Statement

Given is a positive integer N.
Find the number of permutations (P_1,P_2,\cdots,P_{3N}) of (1,2,\cdots,3N) that can be generated through the procedure below.
This number can be enormous, so print it modulo a prime number M.

Make N sequences A_1,A_2,\cdots,A_N of length 3 each, using each of the integers 1 through 3N exactly once.

Let P be an empty sequence, and do the following operation 3N times.

Among the elements that are at the beginning of one of the sequences A_i that is non-empty, let the smallest be x.

Remove x from the sequence, and add x at the end of P.

Constraints

1 \leq N \leq 2000

10^8 \leq M \leq 10^9+7

M is a prime number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of permutations modulo M.

Sample Input 1

1 998244353

Sample Output 1

6

All permutations of length 3 count.

Sample Input 2

2 998244353

Sample Output 2

261

Sample Input 3

314 1000000007

Sample Output 3

182908545

Solution in C++ (GCC 9.2.1) (judge verdict: Accepted)

#include<bits/stdc++.h>
#define For(i,x,y) for (register int i=(x);i<=(y);i++)
#define FOR(i,x,y) for (register int i=(x);i<(y);i++)
#define Dow(i,x,y) for (register int i=(x);i>=(y);i--)
#define Debug(v) for (auto i:v) printf("%lld ",i);puts("")
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define ep emplace_back
#define siz(x) ((int)(x).size())
#define all(x) (x).begin(),(x).end()
#define fil(a,b) memset((a),(b),sizeof(a))
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pa;
typedef pair<ll,ll> PA;
typedef vector<int> poly;
inline ll read(){
    ll x=0,f=1;char c=getchar();
    while ((c<'0'||c>'9')&&(c!='-')) c=getchar();
    if (c=='-') f=-1,c=getchar();
    while (c>='0'&&c<='9') x=x*10+c-'0',c=getchar();
    return x*f;
}

const int N = 6010;
int n,mod,f[N][2*N];

inline void upd(int &x,int y){
	x+=y;
	if (x>=mod) x-=mod;
}

int main(){
	n=read()*3,mod=read();
	f[0][N]=1;
	FOR(i,0,n) For(j,N-i,N+i) if (f[i][j]){
		upd(f[i+1][j+1],f[i][j]);
		f[i+2][j-1]=(f[i+2][j-1]+1ll*f[i][j]*(i+1))%mod;
		f[i+3][j]=(f[i+3][j]+1ll*f[i][j]*(i+1)%mod*(i+2))%mod;
	}
	int ans=0;
	For(i,N,N+n) upd(ans,f[n][i]);
	printf("%d\n",ans);
}