codeforces1013D - 并查集

版权声明:本文为博主原创文章,未经博主允许不得转载,如需转载请注明出处。 https://blog.csdn.net/qq_36889101/article/details/81385508

Chemical table

题目大意

对于一个n*m的矩阵中给你q个点,现在对于如下形式是可以转换的
img

问你还需添加多少个点可以使得所有点都被填满。

数据范围

1 n , m 200000 , 0 q m i n ( n m , 200000 ) , 1 r i n , 1 c i m

解题思路

首先对于所有第a行的被填过的点设为集合S,如果b行的某个点的与S中的某点同列,那么对应就能填上所有在b行与集合S同列的点,相应的对于列也是一样。那么这些行和列就能被看做为一个集合,当两个集合合并时,只需要添加一个点就能使得两个集合合并,所以最后答案就是集合个数减一。

AC代码

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn = 200000;
int n, m, q;
int fa[maxn * 2 + 5];
int Find(int x) {
    if(fa[x] == x)return x;
    return fa[x] = Find(fa[x]);
}
void Union(int x, int y) {
    x = Find(x);
    y = Find(y);
    if(x != y)fa[y] = x;
}
int main() {
    scanf("%d%d%d", &n, &m, &q);
    for(int i = 1; i <= n + m; i++)fa[i] = i;
    for(int i = 1; i <= q; i++) {
        int r, c; scanf("%d%d", &r, &c);
        Union(r, n + c);
    }
    int cnt = 0;
    for(int i = 1; i <= n + m; i++)if(fa[i] == i)cnt++;
    printf("%d\n", cnt - 1);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36889101/article/details/81385508