Swap Swap Sort
Time limit3sMemory limit512 MB
Maintain a target permutation of 1..K under adjacent swaps, and after each swap report the minimum adjacent-swap count to sort the fixed array by that ordering.
- Level
Hard8 of 10
- Topics
- Sorting, Hash map, Math, Implementation
- Solved
- No attempts yet
Problem
There is an array of N integers, each with a value between 1 and K. Your friend has an algorithm that can sort this array according to any ordering of the numbers from 1 to K. The algorithm performs a sequence of swap operations, which exchange two adjacent elements of the array. The algorithm performs exactly the minimum number of such swaps needed to sort the array.
The desired ordering of the numbers from 1 to K is given by a target permutation. A target permutation is a sequence in which each number from 1 to K appears exactly once, in the order desired by the corresponding ordering.
For example, the array [1 4 2 1 2] sorted by the target permutation 4, 1, 2, 3 results in the array [4 1 1 2 2].
You are interested in the number of swaps your friend's algorithm performs for different target permutations. To explore this, you start with the target permutation 1, 2, ..., K and perform Q operations on it. Each operation swaps two adjacent elements of the target permutation. After each operation, find the number of swaps your friend's algorithm would perform if it ran with the current target permutation. The Q operations change the target permutation cumulatively, but do not affect the array.
Input
The first line contains the three integers N, K, and Q (1 ≤ K ≤ N ≤ 100 000, 1 ≤ Q ≤ 1 000 000).
The next line contains N integers a1, a2, ..., aN (1 ≤ ai ≤ K) specifying the array.
The next Q lines each contain a single integer j (1 ≤ j ≤ K-1), representing the operation of swapping the elements of the target permutation at indices j and j + 1.
Output
For each of the Q operations, output a line containing a single integer: the answer for the current target permutation.
Hint
The three target permutations are 1, 2, 4, 3, then 1, 4, 2, 3, then 4, 1, 2, 3. For the final target permutation, your friend's algorithm uses two swaps to sort the array [1 4 2 1 2] to [4 1 1 2 2].