# 02:宗教信仰

```10 9
1 2
1 3
1 4
1 5
1 6
1 7
1 8
1 9
1 10
10 4
2 3
4 5
4 8
5 8
0 0```

```Case 1: 1
Case 2: 7

``` 1 #include<iostream>
2 #include<cstdio>
3 #include<cstring>
4 #include<algorithm>
5 using namespace std;
6 const int MAXN=50001;
8 {
9     char c='+';int x=0;bool flag=0;
10     while(c<'0'||c>'9'){c=getchar();if(c=='-')flag=1;}
11     while(c>='0'&&c<='9')
12     x=(x<<1)+(x<<3)+c-48,c=getchar();
13     flag==1?n=-x:n=x;
14 }
15 int n,m;
16 int fa[MAXN];
17 bool vis[MAXN];
18 int find(int x)
19 {
20     if(fa[x]==x)
21         return fa[x];
22     return fa[x]=find(fa[x]);
23 }
24 void unionn(int x,int y)
25 {
26     int fx=find(x);
27     int fy=find(y);
28     fa[fx]=fy;
29 }
30 int tot=0;
31 int main()
32 {
33     while(scanf("%d%d",&n,&m))
34     {
35         if(n==0&&m==0)break;
36         for(int i=1;i<=n;i++)
37             fa[i]=i;
38         memset(vis,0,sizeof(vis));
39
40         for(int i=1;i<=m;i++)
41         {
42             int x,y;
44             if(find(x)!=find(y))
45                 unionn(x,y);
46         }
47         int ans=0;
48         for(int i=1;i<=n;i++)
49         {
50             if(vis[find(i)]==0)
51             {
52                 vis[find(i)]=1;
53                 ans++;
54             }
55         }
56         printf("Case %d: %d\n",++tot,ans);
57     }
58     return 0;
59 } ```

1811 篇文章115 人订阅

0 条评论