#t144. 排队调整

排队调整

Queue Reordering

Problem Description

During a PE class, nn students line up in a queue. From front to back, the ii-th student has height hih_i and weight wiw_i. The current lineup looks uneven, and the teacher wants the students to stand in order of decreasing height, and among students of the same height, in order of decreasing weight. When rearranging the queue, only two adjacent students may be swapped at a time. The teacher wants to know the minimum number of swaps needed to arrange the queue into the target order.

Input Format

The first line contains a positive integer nn, the number of students.

The following nn lines each contain two positive integers hih_i and wiw_i, the height and weight of the ii-th student.

Output Format

Output one line containing one integer: the minimum number of swaps needed.

Sample Input 1

5
1 60
3 70
2 80
4 55
4 50

Sample Input 2

5
4 0
4 0
2 0
3 0
1 0

Sample Output 1

8

Sample Output 2

1

Sample Explanation

For the first sample, the target order is: the student of height 44 and weight 5555 stands first, then the student of height 44 and weight 5050, then height 33 weight 7070, then height 22 weight 8080, and finally height 11 weight 6060. Replace each student in the initial queue by his position index in the target queue; the initial sequence becomes [4,2,3,0,1][4, 2, 3, 0, 1]. The minimum number of adjacent swaps to sort this sequence equals the number of inversions in it. The sequence [4,2,3,0,1][4, 2, 3, 0, 1] has inversions: 44 forms 44 pairs with the following 2,3,0,12, 3, 0, 1; 22 forms 22 pairs with 0,10, 1; 33 forms 22 pairs with 0,10, 1; for a total of 88. Therefore at least 88 swaps are needed.

Constraints

For all test cases, 1≤n≤30001 \le n \le 3000 and 0≤hi,wi≤1090 \le h_i, w_i \le 10^9 are guaranteed.