#abc261f. [abc261_f]Sorting Color Balls
[abc261_f]Sorting Color Balls
Problem Statement
There are balls arranged from left to right. The color of the -th ball from the left is Color , and an integer is written on it.
Takahashi wants to rearrange the balls so that the integers written on the balls are non-decreasing from left to right. In other words, his objective is to reach a situation where, for every , the number written on the -th ball from the left is greater than or equal to the number written on the -th ball from the left.
For this, Takahashi can repeat the following operation any number of times (possibly zero):
Choose an integer such that .
If the colors of the -th and -th balls from the left are different, pay a cost of . (No cost is incurred if the colors are the same).
Swap the -th and -th balls from the left.
Find the minimum total cost Takahashi needs to pay to achieve his objective.
Constraints
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
Output
Print the minimum total cost Takahashi needs to pay to achieve his objective, as an integer.
Sample Input 1
5
1 5 2 2 1
3 2 1 2 1
Sample Output 1
6
Let us represent a ball as Color Integer. The initial situation is , , , , . Here is a possible sequence of operations for Takahashi:
- Swap the -st ball (Color ) and -nd ball (Color ). Now the balls are arranged in the order , , , , .
- Swap the -nd ball (Color ) and -rd ball (Color ). Now the balls are arranged in the order , , , , .
- Swap the -rd ball (Color ) and -th ball (Color ). Now the balls are in the order , , , , .
- Swap the -th ball (Color ) and -th ball (Color ). Now the balls are in the order , , , , .
- Swap the -rd ball (Color ) and -th ball (Color ). Now the balls are in the order, , , , .
- Swap the -st ball (Color ) and -nd ball (Color ). Now the balls are in the order , , , , .
- Swap the -nd ball (Color ) and -rd ball (Color ). Now the balls are in the order , , , , .
After the last operation, the numbers written on the balls are from left to right, which achieves Takahashi's objective.
The -st, -nd, -rd, -th, -th, and -th operations incur a cost of each, for a total of , which is the minimum. Note that the -th operation does not incur a cost since the balls are both in Color .
Sample Input 2
3
1 1 1
3 2 1
Sample Output 2
0
All balls are in the same color, so no cost is incurred in swapping balls.
Sample Input 3
3
3 1 2
1 1 2
Sample Output 3
0
Takahashi's objective is already achieved without any operation.