atcoder#CODEFESTIVAL2017QUALCF. Three Gluttons
Three Gluttons
Score : points
Problem Statement
Three men, A, B and C, are eating sushi together. Initially, there are pieces of sushi, numbered through . Here, is a multiple of .
Each of the three has likes and dislikes in sushi. A's preference is represented by , a permutation of integers from to . For each (), A's -th favorite sushi is Sushi . Similarly, B's and C's preferences are represented by and , permutations of integers from to .
The three repeats the following action until all pieces of sushi are consumed or a fight brakes out (described later):
- Each of the three A, B and C finds his most favorite piece of sushi among the remaining pieces. Let these pieces be Sushi , and , respectively. If , and are all different, A, B and C eats Sushi , and , respectively. Otherwise, a fight brakes out.
You are given A's and B's preferences, and . How many preferences of C, , leads to all the pieces of sushi being consumed without a fight? Find the count modulo .
Constraints
- is a multiple of .
- and are permutations of integers from to .
Input
Input is given from Standard Input in the following format:
Output
Print the number of the preferences of C that leads to all the pieces of sushi being consumed without a fight, modulo .
3
1 2 3
2 3 1
2
The answer is two, . In both cases, A, B and C will eat Sushi , and , respectively, and there will be no more sushi.
3
1 2 3
1 2 3
0
Regardless of what permutation is, A and B will try to eat Sushi , resulting in a fight.
6
1 2 3 4 5 6
2 1 4 3 6 5
80
For example, if $(c_1,\ c_2,\ c_3,\ c_4,\ c_5,\ c_6) = (5,\ 1,\ 2,\ 6,\ 3,\ 4)$, A, B and C will first eat Sushi , and , respectively, then they will eat Sushi , and , respectively, and there will be no more sushi.
6
1 2 3 4 5 6
6 5 4 3 2 1
160
9
4 5 6 7 8 9 1 2 3
7 8 9 1 2 3 4 5 6
33600