#ABC214G. [ABC214G] Three Permutations

[ABC214G] Three Permutations

Score : 600600 points

Problem Statement

Given are permutations of (1,,N)(1, \dots, N): p=(p1,,pN)p = (p_1, \dots, p_N) and q=(q1,,qN)q = (q_1, \dots, q_N).

Find the number, modulo (109+7)(10^9 + 7), of permutations r=(r1,,rN)r = (r_1, \dots, r_N) of (1,,N)(1, \dots, N) such that ripir_i \neq p_i and riqir_i \neq q_i for every ii (1iN)(1 \leq i \leq N).

Constraints

  • 1N30001 \leq N \leq 3000
  • 1pi,qiN1 \leq p_i, q_i \leq N
  • pipj(ij)p_i \neq p_j \, (i \neq j)
  • qiqj(ij)q_i \neq q_j \, (i \neq j)
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

NN

p1p_1 \ldots pNp_N

q1q_1 \ldots qNq_N

Output

Print the answer.

4
1 2 3 4
2 1 4 3
4

There are four valid permutations: (3,4,1,2)(3, 4, 1, 2), (3,4,2,1)(3, 4, 2, 1), (4,3,1,2)(4, 3, 1, 2), and (4,3,2,1)(4, 3, 2, 1).

3
1 2 3
2 1 3
0

The answer may be 00.

20
2 3 15 19 10 7 5 6 14 13 20 4 18 9 17 8 12 11 16 1
8 12 4 13 19 3 10 16 11 9 1 2 17 6 5 18 7 14 20 15
803776944

Be sure to print the count modulo (109+7)(10^9 + 7).