Successive questions papers together the roots of plants
Resource limitation
time limit: 2.0s memory limit: 256.0MB
problems described
w planet a plantation, is divided into small squares of m * n (m rows west direction, the north-south direction, n columns). Each frame house planted by co-rooted plants.
This plant has a feature that roots may extend along the north-south or east-west direction, with the plant to synthesize other lattice as a whole.
What if we told you there was a small grid between which the roots phenomenon, you can tell how much strain the roots of plants together in the park a total right?
Input format
number of rows of the first row, two integers m, n, separated by spaces, the grid represents the number of columns (1 <m, n <1000 ).
The next line, an integer k, k represents the following are data lines (0 <k <100000)
Next k rows, the first row two integers a, b, that number is a number of small lattice and small lattice b the root together.
Grid numbers line by line, from top to bottom, left to right number.
For example: 5 * 4 small lattice, ID:
. 1. 3 2 4
5. 6. 8. 7
. 9. 11 10 12 is
13 is 14 15 16
. 17. 19 18 is 20 is
sample input
5 4
16
2. 3
. 1 5
5. 9
4. 8
. 7. 8
. 9 10
10 . 11
. 11 12 is
10 14
12 is 16
14 18 is
. 17 18 is
15. 19
. 19 20 is
. 9 13 is
13 is. 17
sample output
5
Example Description
thereof with reference to the case of FIG engagement root
disjoint-set links Thought
#include<stdio.h>
int pre[1000*1000];
int count=0;
int find(int num){
while(num!=pre[num]){
num = pre[num];
}
return num;
}
void join(int num1,int num2){
if(find(num2)!=find(num1))
pre[find(num2)]=find(num1);
}
int main(){
int m,n,k,num1,num2;
scanf("%d %d",&m,&n);
scanf("%d",&k);
for(int i=1;i<=m*n;i++)
pre[i]=i;
for(int i=1;i<=k;i++){
scanf("%d %d",&num1,&num2);
join(num1,num2);
}
for(int i=1;i<=m*n;i++)
if(find(i)==i){
count++;
}
printf("%d",count);
return 0;
}