Hdu1233 step6.1.4還是暢通工程
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 22072 Accepted Submission(s): 9855
Problem Description
某省調查鄉村交通狀況,得到的統計表中列出了任意兩村莊間的距離。省政府“暢通工程”的目標是使全省任何兩個村莊間都可以實現公路交通(但不一定有直接的公路相連,只要能間接通過公路可達即可),並要求鋪設的公路總長度爲最小。請計算最小的公路總長度。
Input
測試輸入包含若干測試用例。每個測試用例的第1行給出村莊數目N (< 100 );隨後的N(N-1)/2行對應村莊間的距離,每行給出一對正整數,分別是兩個村莊的編號,以及此兩村莊間的距離。爲簡單起見,村莊從1到N編號。
當N爲0時,輸入結束,該用例不被處理。
Output
對每個測試用例,在1行裏輸出最小的公路總長度。
Sample Input
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
Sample Output
3
5
Hint
Hint
Huge input, scanf is recommended.
Source
浙大計算機研究生複試上機考試-2006年
題解:
克魯斯卡爾求最小生成樹,在現有條件下找到最短路徑。
源代碼:
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
struct Road
{
intc1,c2,value;
}rd[10050];
int node[105];
void init()
{
memset(node,-1,sizeof(node));
}
int find_set(int x)
{
if(node[x]== -1)
returnx;
returnnode[x] = find_set(node[x]);
}
bool merge(int x,int y)
{
intr1 = find_set(x);
intr2 = find_set(y);
if(r1== r2)
return0;
if(r1< r2)
node[r2] = r1;
else
node[r1] = r2;
return1;
}
bool mycmp(const Road &x,const Road &y)
{
if(x.value< y.value)
returntrue;
else
returnfalse;
}
int main()
{
intn;
while(scanf("%d",&n) && n)
{
init();
intm = n*(n-1)/2;
for(int i = 0;i < m;i++)
{
scanf("%d%d%d",&rd[i].c1,&rd[i].c2,&rd[i].value);
}
sort(rd,rd+m,mycmp);
intsum = 0,count = 0;
for(int i = 0;i < m;i++)
{
if(merge(rd[i].c1,rd[i].c2))
{
sum += rd[i].value;
count++;
}
if(count== n-1)
break;
}
printf("%d\n",sum);
}
return0;
}