Under construction

Still being built. Things may change

Two Chessboards

Time limit1sMemory limit1024 MB

Summary
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.
Level

Medium7 of 10

Topics
Graph, Greedy
Solved
No attempts yet

Problem

Two N×NN \times N chessboards each have NN 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 rr and column cc as (r,c)(r, c). If the rook at (a,b)(a,b) on board 1 is swapped with the rook at (c,d)(c,d) on board 2, then board 1 gets a rook at (c,d)(c,d), board 2 gets a rook at (a,b)(a,b), 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 (a,b)(a,b), then the rook at (a,b)(a,b) on board 2 cannot be swapped with any rook on board 1 except the one at (a,b)(a,b) 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 NN. (1≤N≤100 0001\leq N\leq 100\ 000)

The next NN lines each contain the row number xix_i and the column number yiy_i of a rook on board 1, separated by a space. (1≤xi,yi≤N1\leq x_i,y_i\leq N)

The next NN lines each contain the row number xix_i and the column number yiy_i of a rook on board 2, separated by a space. (1≤xi,yi≤N1\leq x_i,y_i\leq N)

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 −1-1 instead.

Examples2

  1. Example 1

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

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