luogu#P5089. [eJOI 2018] 元素周期表
[eJOI 2018] 元素周期表
Background
This problem is translated from eJOI2018 Problem D “Chemical table”.
Problem Description
Professors at Innopolis University are working hard on studying the periodic table of elements. They know that there are elements, forming a matrix with rows and columns.
Research shows that if there is an element in the periodic table, element is in the same column as it (but and cannot be in the same row), and element is in the same row as it (but and cannot be in the same column), then scientists can use these three elements to produce a sample of a fourth element by nuclear fusion. Element is in the same row as and in the same column as .
In short, if there are samples of three elements located at in the periodic table (where ), then a sample at can be produced, as shown in the figure:

Note: The samples used in nuclear fusion do not disappear; they can take part in later reactions. Samples obtained from reactions can also take part in reactions.
They have already obtained samples of elements. To collect samples of all elements, they will buy some samples and then use nuclear fusion to produce the remaining ones.
Please find the minimum number of element samples they need to buy.
Input Format
The first line contains integers $n, m, q \ (1 \le n, m \le 2 \times 10^5, 0 \le q \le \min \{n \times m, 2 \times 10^5\})$.
The next lines each contain integers . It is guaranteed that all given elements are distinct.
Output Format
Output one integer, the minimum number of element samples that need to be bought.
2 2 3
1 2
2 2
2 1
0
1 5 3
1 3
1 1
1 5
2
4 3 6
1 2
1 3
2 2
2 3
3 1
3 3
1
Hint
Sample Explanation
Notes
In each sample explanation, there are two matrices.
The first shows the initial state (where crosses mark the elements that already have samples).
The second shows the final state when all samples have been collected (where blue circles represent samples obtained by nuclear fusion, the number inside a blue circle is the order in which it was obtained, and red circles represent purchased samples).
Sample Explanation 1
With the three given elements, a sample of the fourth element can be obtained.

Sample Explanation 2
Since the given elements are only in one row, nuclear fusion cannot be used, so the remaining two element samples can only be purchased.

Sample Explanation 3
The method for collecting all elements is not unique; the following is one possible method. In this method, element can only be obtained after purchasing a sample of element and obtaining a sample of element from reactions.

Subtasks
Note: You will receive the score for a subtask if and only if you pass all test points in that subtask.
| Subtask ID | Score | |||
|---|---|---|---|---|
Translated by ChatGPT 5