cswork / OAOpen practice workspace

MicrosoftOA #46

Minimum Domino Removals

Estimated MediumJudge-ready

Topics (AI-labelled)Subsequences

The order of the dominoes cannot be changed, and they cannot be rotated. Remove some dominoes so that, for every two adjacent kept dominoes, the right value of the first equals the left value of the next. Find the minimum number of removals.

This site uses a standard input/output protocol.

Input

The first line contains N, followed by N lines left right, with values 1..6. This site uses 1≤N≤200000.

Output

Output a single integer, the answer.

Example 1

Input:

5
2 4
1 3
4 6
2 4
1 6

Output:

3

Example 2

Input:

3
1 1
1 1
1 1

Output:

0

Example 3

Input:

2
1 2
3 4

Output:

1

Example notes

Example 1: keep the two dominoes (2,4),(4,6) and remove 3. Example 2: all three dominoes chain together, so remove 0. Example 3: none of them chain, so keep any one and remove 1.

Editorial

Loading solution…