Chemical table
Time limit1sMemory limit512 MB
Given some cells of an n by m grid, fill the rest by purchasing cells and closing 2x2 rectangles; find the minimum number of purchases.
- Level
Hard8 of 10
- Topics
- Union-find, Graph, Matrix, Math
- Solved
- No attempts yet
Problem
Scientists at Innopolis University continue to investigate the periodic table. There are known elements, and they form a periodic table, a rectangle with rows and columns. Each element can be described by its coordinates (, ) in the table. Recently the scientists discovered that for every four different elements in this table that form a rectangle with sides parallel to the sides of the table, if they have samples of three of the four elements, they can produce a sample of the fourth element using nuclear fusion. So if we have elements in positions , , , where and , then we can produce element .

Original samples of elements as well as newly crafted elements can be used again in future fusions.
Scientists at Innopolis University already have samples of elements. They want to obtain samples of all elements. To achieve that, they will purchase some samples from other laboratories and then produce all remaining elements using an arbitrary number of nuclear fusions in some order. Help them find the minimal number of elements they need to purchase.
Input
The first line contains three integers , , (; ), the chemical table dimensions and the number of elements the scientists already have. The following lines contain two integers , (, ) each, descriptions of the elements that the scientists already have. All elements in the input are different.
Output
In the only line print , the minimal number of elements to be purchased.
Notes
The pictures below explain the examples.
The first picture for each example describes the initial set of element samples available. Black crosses represent elements available in the lab initially.
The second picture describes how remaining samples can be obtained. Red dashed circles denote elements that should be purchased from other labs (an optimal solution should minimize the number of red circles). Blue dashed circles are elements which can be produced with nuclear fusion. They are numbered starting in the order in which they can be produced.
Example 1
We can use nuclear fusion and get the element from the other three samples, so we don't need to purchase anything.

Example 2
We cannot use any nuclear fusion at all as there is only one row, so we have to purchase all missing elements.

Example 3
Note that after purchasing one element it's still not possible to produce the middle element in the top row (marked as 4). So we produce the element in the left-bottom corner first (marked as 1), and then use it in future fusions.
