Colourful Permutation Sorting
시간 제한2초메모리 제한1024 MB
각 위치에 색이 있고 원소 두 개를 S의 비용으로 교환하거나 한 색의 위치들을 C_i의 비용으로 마음대로 재배열할 수 있을 때, 순열을 정렬하는 최소 비용을 구한다.
문제
You are given a permutation of integers from to . Each position from to is colored in one of colors. We want to sort the permutation, and for that, we 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.
Note that the positions are colored, not the elements, so when you swap two elements, the positions won't change their colors.
Find the minimum number of coins you need to spend to sort the permutation.
입력
The first line of the input contains a single integer () --- the number of independent test cases you need to process. The description of the test cases follows.
The first line of each test case contains two integers and (, ) --- the size of the permutation and the number of colors.
The second line of each test case contains integers () --- the costs of the operations.
The third line of each test case contains integers (, all are distinct) --- the permutation.
The fourth line of each test case contains integers () --- the colors of the positions.
The sum of over all test cases in one file does not exceed .
출력
For each test case print a single integer --- the minimum number of coins you need to spend to sort the permutation.
힌트
In the first test case, we can sort the permutation by applying the "Swap" operation times: . This way you will spend coins.
Another way to sort it would be to permute all elements on positions of color , but this would cost coins, and we can do cheaper.
In the second test case (which differs from the first one only in the costs of operations), however, it's cheaper to just permute all elements on positions of color , spending coin on this.
In the third test case, one of the optimal sequences of operations would be the following:
- Permute the elements on positions of color to obtain the permutation . This operation costs coin.
- Swap elements . The permutation is now . This operation costs coins.
- Permute the elements on positions of color to obtain the permutation . This operation costs coin.
In total, we spent coins.
In the fourth test case, the permutation is already sorted, so we don't have to spend anything.