#abc261f. F - Sorting Color Balls
F - Sorting Color Balls
Score : points
问题描述
有 个球从左到右排列。左边第 个球的颜色为颜色 ,并且上面写有一个整数 。
高桥希望重新排列这些球,使得球上所写的整数从左到右非严格递增。换句话说,他的目标是达到这样一个状态:对于所有 ,左边第 个球上所写的数字大于或等于左边第 个球上的数字。
为了实现这一目标,高桥可以任意次数(包括零次)重复以下操作:
选择一个整数 ,满足 。
若左边第 个球和第 个球的颜色不同,则需支付成本 (如果颜色相同则不产生成本)。
将左边第 个球与第 个球交换位置。
请找出高桥需要支付的最小总成本以达成他的目标。
以上为通义千问 qwen-max 翻译,仅供参考。
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.
update @ 2024/3/10 11:04:48