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;
typedef bool boolean;

const int N = 6005;

#define ll long long

void exgcd(int a, int b, int& x, int& y) {
	if (!b) {
		x = 1, y = 0;
	} else {
		exgcd(b, a % b, y, x);
		y -= (a / b) * x;
	}
}

int inv(int a, int n) {
	int x, y;
	exgcd(a, n, x, y);
	return (x < 0) ? (x + n) : (x);
}

int Mod;

class Z {
	public:
		int v;

		Z() : v(0) {	}
		Z(int x) : v(x){	}
		Z(ll x) : v(x % Mod) {	}

		friend Z operator + (const Z& a, const Z& b) {
			int x;
			return Z(((x = a.v + b.v) >= Mod) ? (x - Mod) : (x));
		}
		friend Z operator - (const Z& a, const Z& b) {
			int x;
			return Z(((x = a.v - b.v) < 0) ? (x + Mod) : (x));
		}
		friend Z operator * (const Z& a, const Z& b) {
			return Z(a.v * 1ll * b.v);
		}
		friend Z operator ~(const Z& a) {
			return inv(a.v, Mod);
		}
		friend Z operator - (const Z& a) {
			return Z(0) - a;
		}
		Z& operator += (Z b) {
			return *this = *this + b;
		}
		Z& operator -= (Z b) {
			return *this = *this - b;
		}
		Z& operator *= (Z b) {
			return *this = *this * b;
		}
		friend boolean operator == (const Z& a, const Z& b) {
			return a.v == b.v;
		} 
};

typedef Z Zi;

int n;
Zi Inv[N];
Zi f[N][6015];

int main() {
	scanf("%d%d", &n, &Mod);
	const int off = 3005;
	f[0][off] = 1;
	Inv[0] = 0, Inv[1] = 1;
	int n3 = n * 3;
	for (int i = 2; i <= n3; i++) {
		Inv[i] = -Inv[Mod % i] * (Mod / i);
	}
	for (int i = 0; i < n3; i++) {
		int L = -(i >> 1), R = min(i, 3005);
		for (int j = L; j <= R; j++) {
			Zi v = f[i][j + off];
			if (!v.v) {
				continue;
			}
			v *= Inv[n3 - i];
			f[i + 3][j + off] += v;
			f[i + 2][j - 1 + off] += v;
			f[i + 1][min(j + 1, off) + off] += v;
		}
	}
	Zi ans = 0;
	for (int i = 0; i <= min(off, n * 3); i++) {
		ans += f[n3][i + off];
	}
	for (int i = 1; i <= n3; i++)
		ans *= i;
	printf("%d\n", ans.v);
	return 0;
}