并查集

#include<iostream>
#include<cstring>
using namespace std;
int a[1005];
int N,M;
int x,y;
int find(int b){
    int r=b;
    while(a[r]>=0){
        r=a[r];
    }
    return r;
}
void un(){
    int fx=find(x);
    int fy=find(y);
    if(fx!=fy){
     if(a[fy]<a[fx]) swap(fx,fy);//路径压缩 a[fx]
+=a[fy]; a[fy]=fx; } } int main(){ while(cin>>N>>M&&N){ memset(a,-1,sizeof(a)); for(int i=0;i<M;i++){ cin>>x>>y; un(); } int sum=0; for(int i=1;i<=N;i++){ if(a[i]<0) sum++; } cout<<sum-1<<endl; cout<<endl; for(int i=1;i<=N;i++){ cout<<i<<" "<<a[i]<<endl; } } }
原文地址:https://www.cnblogs.com/astonc/p/9936964.html