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++14 (GCC 5.4.1) (judge verdict: Accepted)

#include<bits/stdc++.h>
using namespace std;
#define res register int
#define ll long long
//#define cccgift
//#define getchar()(p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
//char buf[1<<21],*p1=buf,*p2=buf;
template<typename T>
inline void read(T &x)
{
    static char ch;bool f=1;
    for(x=0,ch=getchar();!isdigit(ch);ch=getchar()) if(ch=='-') f=0;
    for(;isdigit(ch);x=(x<<1)+(x<<3)+(ch^48),ch=getchar());x=f?x:-x;
}
template<typename T>
void print(T x)
{
    if (x<0) x=-x,putchar('-');
    if (x>9) print(x/10);
    putchar(x%10+48);
}
template<typename T>
inline void print(T x,char ap) {print(x);if (ap) putchar(ap);}
template<typename T>
inline void chkmax(T &x,const T &y) {x=x<y?y:x;}
template<typename T>
inline void chkmin(T &x,const T &y) {x=x<y?x:y;}
int n,mod,tot,fac[6001],mi2[6001],mi3[6001],inv[6001];
inline int kuai(int p,int q,int mod) {int tot=1;for(;q;p=(ll)p*p%mod,q>>=1) if(q&1) tot=(ll)tot*p%mod;return tot;}
#define inc(x,y) x+=y,x>=mod?x-=mod:0
int main()
{
	read(n),read(mod),fac[0]=mi2[0]=mi3[0]=1,mi2[1]=kuai(2,mod-2,mod),mi3[1]=kuai(3,mod-2,mod);
	for(res i=1;i<=3*n;++i) fac[i]=(ll)fac[i-1]*i%mod;
	inv[3*n]=kuai(fac[3*n],mod-2,mod);
	for(res i=3*n-1;~i;--i) inv[i]=(ll)inv[i+1]*(i+1)%mod;
	for(res i=2;i<=3*n;++i) mi2[i]=(ll)mi2[i-1]*mi2[1]%mod,mi3[i]=(ll)mi3[i-1]*mi3[1]%mod;
	for(res i=0;i<=n;++i)
	  for(res j=0;j<=n-i;++j) //3*n-3i-2j>=j
	  	inc(tot,(ll)mi3[i]*mi2[j]%mod*inv[i]%mod*inv[j]%mod*inv[3*n-3*i-2*j]%mod);
	print((ll)tot*fac[3*n]%mod,'\n');  
	return 0;
}
/* stuff you should look for
    * int overflow, array bounds
    * special cases (n=1?), set tle
    * do something instead of nothing and stay organized
*/