Two Chessboards
Time limit1sMemory limit1024 MB
Given two N by N boards with N rooks each, find the minimum number of rook swaps between the boards so that no rook attacks another on either board, or print -1 if impossible.
Problem
Two chessboards each have rooks on them. A rook can attack another rook in the same row or the same column of the same board.
Swap rooks between the two boards so that no rook on either board attacks another rook.
A swap works as follows. Write a square in row and column as . If the rook at on board 1 is swapped with the rook at on board 2, then board 1 gets a rook at , board 2 gets a rook at , and the two rooks at their original squares are removed.
Each square holds at most one rook. So if a square already has a rook where a swapped rook would land, that existing rook cannot be swapped. For example, if board 1 has a rook at , then the rook at on board 2 cannot be swapped with any rook on board 1 except the one at on board 1.
What is the minimum number of swaps needed so that no rook on either board can attack another rook?
Input
The first line contains an integer . ()
The next lines each contain the row number and the column number of a rook on board 1, separated by a space. ()
The next lines each contain the row number and the column number of a rook on board 2, separated by a space. ()
No coordinate is given twice on the same board.
Output
Print the minimum number of swaps needed so that no rook on either board can attack another rook.
If no sequence of swaps can reach a state where no rook on either board can attack another rook, print instead.