#FT0000067. Sắp xếp bóng theo số và màu (Sorting Color Balls)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Sắp xếp bóng theo số và màu (Sorting Color Balls)
Sorting Color Balls
Source: AtCoder
Version: Phuoc Hung OJ Extended
Problem Statement
There are balls arranged in a row from left to right. Ball has color and carries an integer . You want to rearrange them so that the printed integers are non-decreasing from left to right; equal integers may appear in any relative order.
In one operation, swap two adjacent balls. The operation costs if their colors differ, and if their colors are the same. Any number of operations is allowed.
Find the minimum total cost to achieve non-decreasing printed values. This is a cost-minimization task, not a minimization of the swap count.
Input
The first line contains .
The second line contains integers , the colors of the balls.
The third line contains integers , the printed integers.
Output
Print one integer: the minimum total cost.
Subtasks
-
Subtask 1 (20 points): ; ; for all balls.
-
Subtask 2 (30 points): ; ; for all balls.
-
Subtask 3 (50 points): ; ; for all balls.
Examples
Input
5
1 5 2 2 1
3 2 1 2 1
Output
6
Explanation
Initially the balls as are . We need printed values in non-decreasing order, such as .
There are six value-inverted pairs with different colors: ball with balls ; ball with balls ; and ball with ball . Every such pair must reverse its relative order through adjacent swaps, costing at least in total.
A stable adjacent sorting sequence can reverse precisely value-inverted pairs, with same-color swaps free. Thus a cost of is attainable and is minimum.