其他分享
首页 > 其他分享> > UESTC2021暑假前集训(并查集)

UESTC2021暑假前集训(并查集)

作者:互联网

 

 

 

 

 

 

这是一道非常好的考思维的题目。刚看到这题的第一反应是二分图匹配,但是一看数据范围2e5还是算了吧。正解是并查集,我们可以看到这题很巧妙的设计是一个小朋友有且仅会喜欢两个玩具,这样喜欢了同一个玩具的两个小孩就建立了联系,并且可以和玩具建立一一对应关系,这种一一对应关系为后面的统计答案埋下了伏笔。

所以下次遇到这种分了小块的两两间建立联系的可以考虑用并查集求解。

 

 1 #include <cstdio>
 2 #include <cmath>
 3 #include <cstring>
 4 #include <cstdlib>
 5 #include <queue>
 6 #include <stack>
 7 #include <vector>
 8 #include <iostream>
 9 #include "algorithm"
10 using namespace std;
11 const int MAX=2e5+5;
12 int n,m,fa[MAX],ans;
13 inline int read(){
14     int an(0),x=1;char c=getchar();
15     while (c<'0' || c>'9') {if (c=='-') x=-1;c=getchar();}
16     while (c>='0' && c<='9') {an=(an<<3)+(an<<1)+c-'0';c=getchar();}
17     return an*x;
18 }
19 int getfather(int x){return fa[x]==x?x:fa[x]=getfather(fa[x]);}
20 int main(){
21     freopen ("y.in","r",stdin);
22     freopen ("y.out","w",stdout);
23     int i,j,x,y,tx,ty,an=0;
24     m=read(),n=read();
25     for (i=1;i<=m;i++) fa[i]=i;
26     for (i=1;i<=n;i++){
27         x=read(),y=read();
28         tx=getfather(x);
29         ty=getfather(y);
30         if (tx!=ty){
31             an++;
32             fa[tx]=ty;
33         }
34     }
35     printf("%d",n-an);
36     return 0;
37 }

 

标签:int,查集,while,玩具,UESTC2021,include,集训,getchar
来源: https://www.cnblogs.com/keximeiruguo/p/14792207.html