codeforces1012 B. Chemical table(并查集+思维)

B. Chemical table

One of the way to solve this problem is to interprete the cells in 2d matrix as an edge in the bipartite graph, that is a cell (i, j) is an edge between i of the left part and j of the right part.

将行号放一边,列号放一边构造一个二分图,如果表格中有一点(r,c)意味着二分图左端r向右端c连一条边。

Note, that each fusion operation (we have edges (r1, c1), (r1, c2), (r2, c1) and get edge (r2, c2)) doesn’t change the connected components of the graph.

题目中给的这个意思是不改变当前图的连通性。

然后需要求还需要最少的点数是的n+m个点联通(行n个点,列m个点)

#include<bits/stdc++.h>
using namespace std;
using ll=long long;
template <class T=int> T rd()
{
    T res=0;T fg=1;
    char ch=getchar();
    while(!isdigit(ch)) {if(ch=='-') fg=-1;ch=getchar();}
    while( isdigit(ch)) res=(res<<1)+(res<<3)+(ch^48),ch=getchar();
    return res*fg;
}
const int N=400010;
int fa[N];
int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}
int merge(int x,int y)
{
    if(find(x)==find(y)) return 0;
    fa[find(x)]=find(y);
    return 1;
}
int n,m,q;
int main()
{
    
    n=rd(),m=rd(),q=rd();
    for(int i=1;i<=n+m;i++) fa[i]=i;
    int ans=n+m-1;
    while(q--)
    {
        int r=rd(),c=rd();
        ans-=merge(r,c+n);
    }
    printf("%d\n",ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值