D - Merge Triplets
Editorial
/


Time Limit: 6 sec / Memory Limit: 1024 MB
配点 : 1200 点
問題文
正整数 N が与えられます。 (1,2,\cdots,3N) の順列 (P_1,P_2,\cdots,P_{3N})であって、次の操作によって生成されうるものの数を求めてください。 ただし、答えは非常に大きくなることがあるので、素数 M で割ったあまりを求めてください。
- 長さ 3 の数列を N 個用意する。この数列たちを A_1,A_2,\cdots ,A_N とする。この 3N 個の値には 1 から 3N がちょうど一度ずつ登場せねばならない。
- 空の数列 P を用意する。以下の操作を 3N 回繰り返す。
- 各数列 A_i のうち、空でないものの先頭の要素を見て、そのうち最小の要素を x とする。
- x を A_i から消去する。 P の最後尾に x を追加する。
制約
- 1 \leq N \leq 2000
- 10^8 \leq M \leq 10^9+7
- M は素数
- 入力はすべて整数
入力
入力は以下の形式で標準入力から与えられる。
N M
出力
条件を満たす順列の数を M で割ったあまりを出力せよ。
入力例 1
1 998244353
出力例 1
6
すべての長さ 3 の順列が条件を満たします。
入力例 2
2 998244353
出力例 2
261
入力例 3
314 1000000007
出力例 3
182908545
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