poj2524 Ubiquitous Religions
题目链接:http://poj.org/problem?id=2524
题目的大意是:
在一个学校中有很多宗教,问有多少个不同的宗教派系;
解题思路:
普通并查集问题,用一个变量cnt记录case,其余的是并查集模板

1 #include<iostream>//poj2524 2 #include<algorithm> 3 #include<cstdio> 4 #include<cmath> 5 const int num=5e4+10; 6 int n,m; 7 int s[num]; 8 int cnt; 9 int height[num]; 10 void init_set() 11 { 12 for(register int i=1;i<=n;i++) 13 { 14 s[i]=i; 15 height[i]=0; 16 } 17 } 18 int find_set(int x) 19 { 20 if(x!=s[x]) 21 { 22 s[x]=find_set(s[x]); 23 } 24 return s[x]; 25 } 26 void union_set(int x,int y) 27 { 28 x=find_set(x); 29 y=find_set(y); 30 if(height[x]==height[y]) 31 { 32 height[x]=height[x]+1; 33 s[y]=x; 34 } 35 else 36 { 37 if(height[x]<height[y]) 38 { 39 s[x]=y; 40 } 41 else 42 s[y]=x; 43 } 44 } 45 int main() 46 { 47 while(~scanf("%d %d",&n,&m)) 48 { 49 if(n==0&&m==0) 50 break; 51 init_set(); 52 int ans=0; 53 cnt++; 54 for(register int i=1;i<=m;i++) 55 { 56 int x,y; 57 scanf("%d %d",&x,&y); 58 union_set(x,y); 59 } 60 for(register int i=1;i<=n;i++) 61 { 62 if(s[i]==i) 63 ans++; 64 } 65 printf("Case %d: %d\n",cnt,ans); 66 } 67 return 0; 68 }
本文来自博客园,作者:江上舟摇,转载请注明原文链接:https://www.cnblogs.com/LQS-blog/p/16285558.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步