問題鏈接:HDU1233 還是暢通工程
Problem Description 某省調查鄉村交通狀況,得到的統計表中列出了任意兩村莊間的距離。省政府“暢通工程”的目標是使全省任何兩個村莊間都可以實現公路交通(但不一定有直接的公路相連,只要能間接通過公路可達即可),並要求鋪設的公路總長度爲最小。請計算最小的公路總長度。
Input 測試輸入包含若干測試用例。每個測試用例的第1行給出村莊數目N ( < 100 );隨後的N(N-1)/2行對應村莊間的距離,每行給出一對正整數,分別是兩個村莊的編號,以及此兩村莊間的距離。爲簡單起見,村莊從1到N編號。
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 |
問題分析:這是一個最小生成樹的爲問題,解決的算法有Kruskal(克魯斯卡爾)算法和Prim(普里姆)算法。本程序使用Kruskal算法實現。使用克魯斯卡爾算法,只需要對所有的邊進行排序後處理一遍即可。程序中使用了並查集,用來判定加入一條邊後會不會產生迴路。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
///////////ac
struct node{
int a;
int b;
int c;
};
bool cmp(node& x,node& y)
{
return x.c<y.c;
}
vector<node> v;
int p[102];
int find(int x)
{
if(p[x]==x)
{
return x;
}
else
{
int y=find(p[x]);
p[x]=y;
return y;
}
}
int main()
{
int n;
while(cin>>n&&n!=0)
{
v.clear();
int m=n*(n-1)/2;
for(int i=0;i<m;i++)
{
node nn;
cin>>nn.a>>nn.b>>nn.c;
v.push_back(nn);
}
sort(v.begin(),v.end(),cmp);
for(int i=0;i<=n;i++)
{
p[i]=i;
}
int s=0;
for(int i=0;i<m;i++)
{
int x=find(v[i].a);
int y=find(v[i].b);
if(x!=y)
{
p[x]=y;
s+=v[i].c;
}
}
cout<<s<<endl;
}
return 0;
}