#P5089. Innopolis Element Fusion

    ID: 18327 Type: Default 1000ms 256MiB

Innopolis Element Fusion

Innopolis Element Fusion

In Innopolis University, researchers are studying the periodic table which is organized as an n × m matrix. They discovered an interesting nuclear fusion reaction: if there exist samples of elements at positions \( (r_1, c_1) \), \( (r_1, c_2) \) and \( (r_2, c_1) \) (with \( r_1 \neq r_2 \) and \( c_1 \neq c_2 \)), then one can obtain a sample at position \( (r_2, c_2) \). In formula, if we have:

[ A = (r_1, c_1), \quad B = (r_1, c_2), \quad C = (r_2, c_1) \quad (r_1 \neq r_2,; c_1 \neq c_2), ]

then the reaction produces:

[ D = (r_2, c_2). ]

Note that in a fusion reaction, the samples used are not consumed; they can be used again, and the newly generated sample can participate in later reactions.

The researchers have already obtained samples of q elements from the periodic table. In order to eventually have a sample of every element (i.e. all n × m elements), they are willing to purchase some additional samples and then use nuclear fusion to generate the remaining ones.

Your task is to determine the minimum number of samples that must be purchased so that, by applying the fusion reaction repeatedly, every element in the table can be obtained.

Important: You may choose the positions to purchase the samples arbitrarily. Note that even if every row and every column already has at least one sample, a fusion reaction cannot occur unless there is at least one row containing at least two samples. In the case when no sample exists initially, you must purchase at least n + m − 1 samples to start the fusion process.

inputFormat

The first line contains three integers n, m, and q (1 ≤ n, m ≤ 10^5, 0 ≤ q ≤ n*m), representing the number of rows, columns, and the number of pre-obtained samples respectively.

Each of the next q lines contains two integers r and c (1 ≤ r ≤ n, 1 ≤ c ≤ m), indicating that there is a sample at row r and column c in the periodic table. It is guaranteed that all given positions are distinct.

outputFormat

Output a single integer — the minimum number of additional samples that need to be purchased so that, after applying the fusion reaction arbitrarily many times, samples of all n × m elements can be obtained.

sample

2 2 0
3

</p>