1. 程式人生 > >HDU 1232 -暢通工程(並查集)

HDU 1232 -暢通工程(並查集)

題目

http://acm.hdu.edu.cn/showproblem.php?pid=1232

程式碼

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int MAXN=1e3 + 100;
int pre[MAXN],a[MAXN];
int find(int x)
{
    if(pre[x]==x) return x;
    return pre[x]=find(pre[x]);
}
void join(int
x,int y) { int fx=find(x),fy=find(y); if(fx!=fy) pre[fy]=fx; } int main() { int n,i,k; long long a,b,m; while(cin>>n) { if(n==0) break; cin>>m; for(i=1;i<=n;i++) pre[i]=i; while(m--) { cin>>a>>b; join(a,b); } long
long ans=0; for(i=1;i<=n;i++) { if(pre[i]==i) ans++;//如果一個數(城鎮)的父節點是它本身,則說明與其他路不通 } cout<<ans-1<<endl; } return 0; }