Colourful Permutation Sorting
Time limit2sMemory limit1024 MB
Sort a permutation whose positions are colored with k colors, using swaps that cost S or permutations of one color class that cost C_i, minimizing total coins.
- Level
Medium7 of 10
- Topics
- Bit manipulation, Graph, Implementation
- Solved
- No attempts yet
Problem
You are given a permutation of integers from to . Each position from to is colored in one of colors. You want to sort the permutation. You can apply any number of operations of the following types:
- Swap any two elements. This operation costs coins.
- Choose any color , and permute the elements on positions of color as you wish. This operation costs coins.
The positions are colored, not the elements. When you swap two elements, the positions keep their colors. Find the minimum number of coins needed to sort the permutation.
Input
The first line contains a single integer (), the number of test cases.
Each test case starts with a line containing two integers and (, ). The second line contains (). The third line contains the permutation (, all are distinct). The fourth line contains the colors () of the positions.
The sum of over all test cases does not exceed .
Output
For each test case, print the minimum number of coins needed to sort the permutation, one per line.
Hint
In the first test case, applying the swap operation 3 times sorts the permutation: . This costs 3 coins. Permuting all elements at color 1 positions also works, but it costs 10 coins, which is more.
The second test case differs from the first only in operation costs. Here permuting the color 1 positions costs 1 coin, which is cheaper.
In the third test case, an optimal sequence is as follows. First, permute the elements at color 2 positions to get , costing 1 coin. Then swap and , costing 10 coins, to get . Finally, permute the elements at color 1 positions to get , costing 1 coin. The total is 12 coins.
In the fourth test case, the permutation is already sorted, so no coins are spent.