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 <iostream>
#include <vector>
#include <algorithm>
int p;
int power(int base, int e) {
    int res = 1;
    while (e > 0) {
        if (e % 2 == 1)
            res = 1LL * res * base % p;
        base = 1LL * base * base % p;
        e /= 2;
    }
    return res;
}
int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int n;
    std::cin >> n >> p;
    std::vector<int> fac(3 * n + 1), invFac(3 * n + 1), p2(n + 1), p3(n + 1);
    fac[0] = 1;
    for (int i = 1; i <= 3 * n; ++i)
        fac[i] = 1ll * fac[i - 1] * i % p;
    for (int i = 0; i <= 3 * n; ++i)
        invFac[i] = power(fac[i], p - 2);
    p2[0] = 1;
    p2[1] = power(2, p - 2);
    for (int i = 2; i <= n; ++i)
        p2[i] = 1ll * p2[i - 1] * p2[1] % p;
    p3[0] = 1;
    p3[1] = power(3, p - 2);
    for (int i = 2; i <= n; ++i)
        p3[i] = 1ll * p3[i - 1] * p3[1] % p;
    int ans = 0;
    for (int i = 0; i <= n; ++i) {
        for (int j = 0; i + j <= n; ++j) {
            int k = 3 * n - 3 * i - 2 * j;
            ans = (ans + 1ll * p3[i] * invFac[i] % p * p2[j] % p * invFac[j] % p * invFac[k]) % p;
        }
    }
    ans = 1ll * fac[3 * n] * ans % p;
    std::cout << ans << "\n";
    return 0;
}