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

HDU 1232 暢通工程 (並查集)

while name style queue input 結束 inf long 城市

某省調查城鎮交通狀況,得到現有城鎮道路統計表,表中列出了每條道路直接連通的城鎮。省政府“暢通工程”的目標是使全省任何兩個城鎮間都可以實現交通(但不一定有直接的道路相連,只要互相間接通過道路可達即可)。問最少還需要建設多少條道路?

Input測試輸入包含若幹測試用例。每個測試用例的第1行給出兩個正整數,分別是城鎮數目N ( < 1000 )和道路數目M;隨後的M行對應M條道路,每行給出一對正整數,分別是該條道路直接連通的兩個城鎮的編號。為簡單起見,城鎮從1到N編號。
註意:兩個城市之間可以有多條道路相通,也就是說
3 3
1 2
1 2
2 1
這種輸入也是合法的
當N為0時,輸入結束,該用例不被處理。

Output對每個測試用例,在1行裏輸出最少還需要建設的道路數目。
Sample Input

4 2
1 3
4 3
3 3
1 2
1 3
2 3
5 2
1 2
3 5
999 0
0

Sample Output

1
0
2
998
題解:簡單並查集
 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <cstdio>
 5 #include <vector>
 6 #include <cstdlib>
 7
#include <iomanip> 8 #include <cmath> 9 #include <ctime> 10 #include <map> 11 #include <set> 12 #include <queue> 13 using namespace std; 14 #define lowbit(x) (x&(-x)) 15 #define max(x,y) (x>y?x:y) 16 #define min(x,y) (x<y?x:y) 17 #define MAX 100000000000000000 18
#define MOD 1000000007 19 #define pi acos(-1.0) 20 #define ei exp(1) 21 #define PI 3.141592653589793238462 22 #define INF 0x3f3f3f3f3f 23 #define mem(a) (memset(a,0,sizeof(a))) 24 typedef long long ll; 25 ll gcd(ll a,ll b){ 26 return b?gcd(b,a%b):a; 27 } 28 bool cmp(int x,int y) 29 { 30 return x>y; 31 } 32 const int N=10005; 33 const int mod=1e9+7; 34 int f[50002],a,b,m,n,p; 35 int find1(int x){ 36 if(f[x]!=x) 37 f[x]=find1(f[x]); 38 return f[x]; 39 } 40 int main() 41 { 42 int i; 43 while(scanf("%d%d",&n,&m)&&n!=0){ 44 for(i=1;i<=n;i++) 45 f[i]=i; 46 for(i=1;i<=m;i++){ 47 scanf("%d%d",&a,&b); 48 a=find1(a); 49 b=find1(b); 50 f[a]=b; 51 } 52 int t=0; 53 for(i=1;i<=n;i++){ 54 if(find1(i)==i){ 55 t++; 56 } 57 } 58 cout<<t-1<<endl; 59 } 60 return 0; 61 }

HDU 1232 暢通工程 (並查集)