Under construction

Still being built. Things may change

Gathering Colors

Time limit2sMemory limit1024 MB

Summary
Given N boxes with two balls each and one empty box, find the minimum number of moves so that both balls of every color end up in the same box.
Level

Medium7 of 10

Topics
Graph, Implementation, Greedy
Solved
No attempts yet

Problem

There are 2N2N balls and N+1N+1 boxes. Each ball is colored with one of 1,2,⋯ ,N1, 2, \cdots, N, and each color is used on exactly 22 balls. Each box can hold at most 22 balls. At the start, boxes 11 through NN each contain 22 balls, and box N+1N+1 is empty. The color of the top ball in box ii is AiA_i, and the color of the bottom ball is BiB_i.

You can move a ball from one box to another. You remove the top ball of one box and place it on top of another box.

You must move balls so that the two balls of each color end up in the same box. Every move must satisfy one of the following two conditions.

  • The box you place the ball into is completely empty.
  • The box you place the ball into contains exactly one ball, and that ball has the same color as the ball you are moving.

Find the minimum number of moves needed so that balls of the same color are in the same box.

In the figure above, the following moves reach the goal in 66 moves, and it is impossible to do it in fewer moves.

  • Move the ball of color 33 from box 44 to box 66.
  • Move the ball of color 22 from box 33 to box 44.
  • Move the ball of color 44 from box 11 to box 33.
  • Move the ball of color 33 from box 22 to box 66.
  • Move the ball of color 55 from box 55 to box 22.
  • Move the ball of color 11 from box 55 to box 11.

Input

The first line contains NN.

The next NN lines describe the two balls in each box. The ii-th of these lines contains AiA_i and BiB_i, separated by a space.

Output

Print the minimum number of moves needed so that balls of the same color are in the same box. If it is impossible, print −1-1.

Constraints

  • All input values are integers.
  • 1≤N≤200 0001 \le N \le 200\,000
  • 1≤Ai,Bi≤N1 \le A_i, B_i \le N
  • For each ii (1≤i≤N1 \le i \le N), exactly 22 of the values A1,⋯ ,AN,B1,⋯ ,BNA_1, \cdots, A_N, B_1, \cdots, B_N equal ii.

Examples3

  1. Example 1

    Input
    5
    4 1
    3 5
    2 4
    3 2
    5 1
    
    Expected output
    6
    
  2. Example 2

    Input
    2
    1 1
    2 2
    
    Expected output
    0
    
  3. Example 3

    Input
    4
    2 1
    3 1
    2 4
    3 4
    
    Expected output
    -1