#P5749. [IOI 2019] 排列鞋子
[IOI 2019] 排列鞋子
Description
Adnan owns the largest shoe store in Baku. A box containing pairs of shoes has just arrived at his store. Each pair of shoes consists of two shoes of the same size: one left shoe and one right shoe. Adnan lines up these shoes in a row. This row has a total of positions, numbered from to from left to right.
Adnan wants to rearrange these shoes into a valid permutation. A permutation is valid if and only if for all , the following conditions all hold:
- The shoes at positions and have the same size.
- The shoe at position is a left shoe.
- The shoe at position is a right shoe.
To achieve this, Adnan can perform a sequence of swaps. In each swap, he chooses two currently adjacent shoes and swaps them (that is, he picks them up and puts each shoe back into the other shoe’s original position). Two shoes are adjacent if and only if the difference of their position indices is .
Find the minimum number of swaps Adnan needs to obtain a valid permutation.
Input Format
The first line contains a positive integer , meaning there are pairs of shoes.
The second line contains integers . The -th integer describes the shoe whose position index is . Here , and it equals the size of the shoe initially at position . Here denotes the absolute value of : it equals when , and equals when . If , then the shoe at position is a left shoe; otherwise, it is a right shoe.
Output Format
Output one line with one integer, the minimum number of swaps.
2
2 1 -1 -2
4
3
-2 2 2 -2 -2 2
1
Hint
Explanation for Sample 1
Adnan can obtain a valid permutation with swaps.
For example, he can first swap and , then swap and , then swap and . Finally, swap and . After that, he can get a valid permutation. It is impossible to obtain a valid permutation with fewer than swaps, so the output is .

Explanation for Sample 2
Adnan can swap the shoes at positions and to obtain the valid permutation , so the output should be .
Constraints
For all testdata:
- .
- For all , .
- A valid permutation can always be obtained through a sequence of swaps.
The detailed extra constraints and scores for subtasks are shown in the table below:
| Subtask ID | Additional Constraints | Score |
|---|---|---|
| All shoes have the same size. | ||
| All shoes at positions are left shoes, and all shoes at positions are right shoes. Also, for all , the shoes at positions and have the same size. | ||
| No additional constraints. |
Translated by ChatGPT 5
京公网安备 11011102002149号