[EJOI2018] Periodic Table of Elements

topic

\ ((r_1, c_1), (r_2, c_1), (r_1, c_2) \) three grid exists to explain \ ((r_2, c_2) \ ) exists, if we \ (r_1, c_2, c_1, r_2 \) are considered at some point, then this relationship is very similar to \ (r_1 \) and \ (c_1 \) China Unicom, \ (R_2 \) and \ (c_1 \) China Unicom, \ (c_2 \) and \ ( r_1 \) China Unicom, then that \ (r_2 \) and \ (c_2 \) Unicom

So we will each bin \ ((x, y) \ ) as some of the edge, connected \ (x \) line and (y \) \ column, apparently this picture is a bipartite graph, our goal is to up to a complete bipartite graph, i.e. there are \ (n \ times m \) edges

We already have \ (q \) on the sides even, we do not need the expense will be able to find even the sides are in the same block in China Unicom, we complement all unnecessary expense side the most they can put Figure complement into several sub-picture of the complete bipartite graph

While the same side does not require the expense of a link in the block, so we use this as little as possible so that the edges completely Unicom FIG like, to give a clear need for even number of sides is the number of blocks Unicom \ (- 1 \) , and check set maintenance look like a

Code

#include<bits/stdc++.h>
#define re register
inline int read() {
    char c=getchar();int x=0;while(c<'0'||c>'9') c=getchar();
    while(c>='0'&&c<='9') x=(x<<3)+(x<<1)+c-48,c=getchar();return x;
}
const int maxn=2e5+5;
int fa[maxn<<1],n,m,q;
inline int find(int x) {return fa[x]==x?x:fa[x]=find(fa[x]);}
inline void merge(int x,int y) {
    int xx=find(x),yy=find(y);
    if(xx==yy) return;fa[xx]=yy;
}
int main() {
    n=read(),m=read(),q=read();
    for(re int i=1;i<=n+m;++i) fa[i]=i;
    for(re int x,y,i=1;i<=q;i++) 
        x=read(),y=read(),merge(x,y+n);
    int ans=0;
    for(re int i=1;i<=n+m;i++) if(find(i)==i) ans++;
    printf("%d\n",ans-1);
    return 0;
}

Guess you like

Origin www.cnblogs.com/asuldb/p/11488655.html