#P9900. 『PG2』消除萝卜 B

『PG2』消除萝卜 B

Problem Description

There are n×2n\times 2 carrots arranged in two columns. Carrots are either white or red. We use ai,j=0/1a_{i,j}=0/1 to represent whether the carrot in row ii, column jj is white or red.

Each time, you may pay a cost of 11 to choose a position that currently has a carrot, and remove all carrots in the 4-connected maximal connected component consisting of carrots of the same color as that chosen carrot. After that, if a carrot is in row ii and the corresponding position in row i1i-1 has no carrot, then it will fall to row i1i-1.

Also, you may pay a cost that is initially 00 to choose k=1/2k=1/2 and shift all carrots in column kk upward (ai,kai+1,ka_{i,k}\to a_{i+1,k}), and place a red carrot, i.e. 11, into row 11, column kk (1a1,k1\to a_{1,k}). After this, the cost of this operation increases by 11 each time it is used.

Find the minimum total cost to remove all carrots.

Input Format

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

The next nn lines each contain two integers, which are ai,1,ai,2a_{i,1},a_{i,2}.

Output Format

Output one integer in one line, representing your answer.

4
0 1
0 1
0 1
0 1
2
6
1 0
1 0
0 1
0 1
1 0
1 0
3

Hint

For all test points, ai,j{0,1}a_{i,j}\in \{0,1\}, 1n5×1061\leq n\leq 5\times 10^6, and it is guaranteed that ai,1ai,2a_{i,1}\neq a_{i,2}.

This problem uses bundled tests.
$\sf subtask \ 1: n\leq10 \ \ \ \ \ \ \ \ \ \ \ 30pts$
subtask 2:n100         20pts\sf subtask \ 2: n\leq100 \ \ \ \ \ \ \ \ \ 20 pts
subtask 3:n5000       20pts\sf subtask \ 3: n\leq5000 \ \ \ \ \ \ \ 20 pts
subtask 4:n5000000 30pts\sf subtask \ 4: n\leq5000000 \ 30pts

Translated by ChatGPT 5