#P9001. [CEOI 2022] Parking
[CEOI 2022] Parking
Problem Description
Valerija works in the parking lot of a restaurant. She is responsible for politely welcoming important guests, keeping their car keys, and helping them park.
One evening, she found that there were exactly cars in the parking lot she manages. They have different colors, and each color has exactly two cars. We number the colors from to .
The parking lot has parking spots, numbered from to . Each spot can hold two cars and has only one entrance. We call the car closer to the entrance the “top car”, and the one farther from the entrance the “bottom car”. A car can drive out from the entrance if and only if no car blocks it. When parking, Valerija ensures that each spot is either empty, or completely full with two cars, or contains only one bottom car.

This figure shows the first sample and also shows the only first drive.
Valerija wants to rearrange the cars so that each pair of cars with the same color ends up in the same parking spot. We do not care which spot corresponds to which color, and we do not care which car is on top and which is on the bottom. Valerija will perform the following operation:
- Drive a car that can currently leave its spot, and move it to another spot such that:
- the destination spot is empty, and she parks the car in the bottom position, or
- the destination spot contains exactly one car, and that car has the same color as the car being driven.
Valerija wants to know the minimum number of operations and one optimal sequence of operations. Please solve this problem.
Input Format
The first line contains two integers .
The next lines each contain two integers . Here is the color of the car in the bottom position of this spot, and is the color of the car in the top position of this spot. If a value is , it means there is no car in the bottom/top position.
Output Format
If it is impossible to meet the requirement, output one line with a single integer .
Otherwise, output a single integer on the first line, the minimum number of operations.
Then output lines. Each line contains two integers , meaning that in the -th operation, you drive the car that can leave from spot to spot .
Note that the shortest solution may not be unique. You only need to output any one of them.
4 5
1 0
2 0
1 3
4 4
3 2
3
5 2
3 5
3 1
4 5
0 0
2 1
3 1
3 4
2 4
-1
5 7
1 0
2 1
2 3
4 3
5 4
5 0
0 0
6
2 1
3 7
4 7
2 3
5 4
5 6
Hint
Explanation for Sample 1
From the figure in the statement, we can see that this sample has only one solution.
Constraints
For all testdata, .
If your program correctly finds the minimum number of operations but constructs an incorrect sequence, you will get of the score for that test point.
| Subtask ID | Special Constraints | Score |
|---|---|---|
| , each spot is either empty or full. | ||
| each spot is either empty or full. | ||
| no special constraints. |
Translated by ChatGPT 5