All problems

Problem 629

Most Stones Removed with Same Row or Column

Medium · 20 pts · Graph, Union Find, Depth-First Search

Problem

N stones lie on distinct integer points of a grid. A stone can be removed if another stone that is still on the grid shares its row or its column. Find the largest number of stones that can be removed. Link two stones whenever they share a row or a column; within each connected group you can always remove stones one by one until a single stone remains, so the answer is N minus the number of groups. Union-find over the rows and columns does this in nearly linear time.

Input

The first line contains N. Each of the next N lines contains the coordinates x y of a stone.

Output

Print the maximum number of stones that can be removed.

Constraints

1 <= N <= 1000; 0 <= x, y <= 10000; no two stones share both coordinates

Example input

6
0 0
0 1
1 0
1 2
2 1
2 2

Example output

5

Explanation

The stones (0,0), (0,1), (1,0), (1,2), (2,1) and (2,2) are all linked through shared rows and columns, forming one group. All but one can be removed, so the answer is 5.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Course Schedule IV Next: Regions Cut By Slashes