Gathering Colors
Time limit2sMemory limit1024 MB
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 balls and boxes. Each ball is colored with one of , and each color is used on exactly balls. Each box can hold at most balls. At the start, boxes through each contain balls, and box is empty. The color of the top ball in box is , and the color of the bottom ball is .
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 moves, and it is impossible to do it in fewer moves.
- Move the ball of color from box to box .
- Move the ball of color from box to box .
- Move the ball of color from box to box .
- Move the ball of color from box to box .
- Move the ball of color from box to box .
- Move the ball of color from box to box .
Input
The first line contains .
The next lines describe the two balls in each box. The -th of these lines contains and , 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 .
Constraints
- All input values are integers.
- For each (), exactly of the values equal .