#codefestival2017qualcf. [code_festival_2017_qualc_f]Three Gluttons
[code_festival_2017_qualc_f]Three Gluttons
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 .
Sample Input 1
3
1 2 3
2 3 1
Sample Output 1
2
The answer is two, $(c_1,\\ c_2,\\ c_3) = (3,\\ 1,\\ 2),\\ (3,\\ 2,\\ 1)$. In both cases, A, B and C will eat Sushi , and , respectively, and there will be no more sushi.
Sample Input 2
3
1 2 3
1 2 3
Sample Output 2
0
Regardless of what permutation is, A and B will try to eat Sushi , resulting in a fight.
Sample Input 3
6
1 2 3 4 5 6
2 1 4 3 6 5
Sample Output 3
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.
Sample Input 4
6
1 2 3 4 5 6
6 5 4 3 2 1
Sample Output 4
160
Sample Input 5
9
4 5 6 7 8 9 1 2 3
7 8 9 1 2 3 4 5 6
Sample Output 5
33600