求救0分
  • 板块P1536 村村通
  • 楼主BL8083
  • 当前回复3
  • 已保存回复3
  • 发布时间2023/5/23 18:01
  • 上次更新2023/10/23 14:56:42
查看原帖
求救0分
913282
BL8083楼主2023/5/23 18:01
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1005;
int n,m,x,y;
int f[MAXN];
void init(int f[])
{
    for(int i=0;i<=MAXN-1;i++) f[i]=i;
}
int find_f(int x, int f[])
{
    if(x!=f[x]) return f[x]=find_f(f[x],f);
    return f[x];
}
void join(int x,int y,int f[])
{
    int fx=find_f(x,f),fy=find_f(y,f);
    if(fx!=fy) f[fy]=fx;
}
int main()
{
    while(true)
    {
        int ans=0;
        cin>>n;
        if(n!=0)
        {
            cin>>m;
            init(f);
            for(int i=1;i<=m;i++) 
                cin>>x>>y;
                join(x,y,f);
            int cnt = 0;
            for (int i = 1; i <= n; i++) 
                if (f[i] == i) cnt++;
            cout<<cnt-1<<endl;
            //for(int i=1;i<=n;i++) f[i]=i;    
        }else{
            break;
        }
    }
    return 0;
}
2023/5/23 18:01
加载中...