Double Derangement

시간 제한1초메모리 제한1024 MB

요약
모든 i에서 c[i]가 a[i]와 b[i] 모두와 다른 순열 c의 개수를 센다. N은 최대 16이다.
난이도

어려움10점 중 8점

유형
동적 계획법, 비트 연산, 조합론, 완전 탐색
정답자
아직 제출이 없습니다

문제

You are given two permutations aa and bb, each of length NN containing every integer in the range \[1,N]\[1,N]. Your task is to construct a new permutation cc of length NN that contains every integer in the range \[1,N]\[1,N], such that for every index ii (11-indexed), the following condition is satisfied:

\[c_i \neq a_i \quad \text{and} \quad c_i \neq b_i.\]

In other words, for no index ii can c_ic\_i be equal to a_ia\_i or b_ib\_i​.

Given the permutations aa and bb, determine how many such permutations cc exist.

입력

The first line of input contains a single integer TT, denoting the number of test cases.

For each test case, the input is as follows:

  • The first line of each test case contains a single integer, NN, denoting the length of the permutations. (1≤N≤161 \le N \le 16)
  • The next line contains NN space-separated integers, denoting the permutation aa. Here, the ii-th integer denotes a_ia\_i​. (1≤a_i≤N;1 \le a\_i \le N; i≠j→a_i≠a_ji \ne j \rightarrow a\_i \ne a\_j​)
  • The next line contains NN space-separated integers, denoting the permutation bb. Here, the ii-th integer denotes b_ib\_i​. (1≤b_i≤N;1 \le b\_i \le N; i≠j→b_i≠b_ji \ne j \rightarrow b\_i \ne b\_j)

Sum of NN over all cases ≤2,000\le 2\\,000.

출력

Output how many such permutations cc described in the problem exist.

힌트

You may have to use a type larger than a 3232-bit integer to prevent overflow in this problem.

예제1

  1. 예제 1

    입력
    1
    4
    1 2 3 4
    2 3 1 4
    
    예상 출력
    3