Double Derangement
InterviewTime limit1sMemory limit1024 MB
Given two permutations a and b of length N (up to 16), count the permutations c where c_i differs from both a_i and b_i at every index.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Bit manipulation
- Solved
- No attempts yet
Problem
You are given two permutations and , each of length . Each permutation contains every integer in the range exactly once. Construct a new permutation of length that contains every integer in the range , such that for every index (-indexed), the following condition holds.
In other words, can never equal or at the same index. Given and , count the permutations that satisfy this condition.
Input
The first line contains a single integer , the number of test cases.
Each test case is given as follows. The first line contains a single integer , the length of the permutations. The next line contains space-separated integers, the permutation , where the -th integer is . The next line contains space-separated integers, the permutation , where the -th integer is .
Constraints: ; ; ; within each permutation, all values are distinct. The sum of over all test cases is at most .
Output
For each test case, output the number of permutations that satisfy the condition.
Hint
You may have to use a type larger than a 32-bit integer to prevent overflow.