标准并查集
求有几个独立区间
减一即可
#include <iostream>
using namespace std;
const int MAXN = 1e4 + 10;
int arr[MAXN];
void init(int N)
{
for(int i = 1; i <= N; i++)
arr[i] = i;
}
int find(int x)
{
if(arr[x] == x)
return x;
return arr[x] = find(arr[x]);
}
void join(int x,int y)
{
x = find(x), y = find(y);
if(x != y)
{
arr[x] = y;
}
}
int cal(int N)
{
int ans = 0;
for(int i = 1; i <= N; i++)
if(find(i) == i)
ans ++;
return ans;
}
int main()
{
ios::sync_with_stdio(false);
int N, M, x, y;
while(cin>>N && N)
{
init(N);
cin>>M;
while(M--)
{
cin>>x>>y;
join(x, y);
}
cout<<cal(N) - 1<<endl;
}
return 0;
}