暢通工程
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 44510 Accepted Submission(s): 23595
Problem Description
某省調查城鎮交通狀況,得到現有城鎮道路統計表,表中列出了每條道路直接連通的城鎮。省政府“暢通工程”的目標是使全省任何兩個城鎮間都可以實現交通(但不一定有直接的道路相連,只要互相間接通過道路可達即可)。問最少還需要建設多少條道路?
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
Hint
Hint
Huge input, scanf is recommended.
Source
浙大計算機研究生複試上機考試-2005年
Recommend
JGShining | We have carefully selected several similar problems for you: 1233 1272 1875 1879 1213
來源: http://acm.hdu.edu.cn/showproblem.php?pid=1232
#include <iostream>
#include <cstdio>
#include <map>
#include <set>
#include <algorithm>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <queue>
using namespace std;
#define MAXN 1000
int par[MAXN],Rank[MAXN];
//並查集模板---------------------------------------------
void init(int n)
{
for(int i=1;i<=n;i++)
{
par[i]=i;
Rank[i]=0;
}
}
int Find(int x)
{
if(par[x]==x) return x;
else return par[x]=Find(par[x]); ///同時壓縮路徑
}
void unite(int x,int y)
{
x=Find(x);y=Find(y);
if(x==y) return;
if(Rank[x]<Rank[y]) par[x]=y;
else par[y]=x;
if(Rank[x]==Rank[y]) Rank[x]++;
}
----------------------------------------------------//
int main()
{
//freopen("F:\\test.txt","r",stdin);
int N,M;
while(~scanf("%d %d",&N,&M)&&N)
{
init(N);
for(int i=1,a,b;i<=M&&scanf("%d %d",&a,&b);i++)
unite(a,b);
int Count=0;
for(int i=1;i<=N;i++)
if(par[i]==i) Count++; printf("%d\n",Count-1); //N個單獨塊用n-1條線連
}
return 0;
}