标签:int 查集 while 玩具 UESTC2021 include 集训 getchar
这是一道非常好的考思维的题目。刚看到这题的第一反应是二分图匹配,但是一看数据范围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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。