PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000067. Sắp xếp bóng theo số và màu (Sorting Color Balls)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

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 NN balls arranged in a row from left to right. Ball ii has color CiC_i and carries an integer XiX_i. 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 11 if their colors differ, and 00 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 NN.

The second line contains NN integers C1,…,CNC_1,\ldots,C_N, the colors of the balls.

The third line contains NN integers X1,…,XNX_1,\ldots,X_N, the printed integers.

Output

Print one integer: the minimum total cost.

Subtasks

  • Subtask 1 (20 points): 2≤N≤602\le N\le 60; 1≤Ci≤N1\le C_i\le N; 1≤Xi≤N1\le X_i\le N for all balls.

  • Subtask 2 (30 points): 2≤N≤30002\le N\le 3000; 1≤Ci≤N1\le C_i\le N; 1≤Xi≤N1\le X_i\le N for all balls.

  • Subtask 3 (50 points): 2≤N≤3000002\le N\le 300000; 1≤Ci≤N1\le C_i\le N; 1≤Xi≤N1\le X_i\le N for all balls.

Examples

Input

5
1 5 2 2 1
3 2 1 2 1

Output

6

Explanation

Initially the balls as (color,number)(color,number) are (1,3),(5,2),(2,1),(2,2),(1,1)(1,3),(5,2),(2,1),(2,2),(1,1). We need printed values in non-decreasing order, such as [1,1,2,2,3][1,1,2,2,3].

There are six value-inverted pairs with different colors: ball 11 with balls 2,3,42,3,4; ball 22 with balls 3,53,5; and ball 44 with ball 55. Every such pair must reverse its relative order through adjacent swaps, costing at least 66 in total.

A stable adjacent sorting sequence can reverse precisely value-inverted pairs, with same-color swaps free. Thus a cost of 66 is attainable and is minimum.