題目描述:
現有村落間道路的統計數據表中,列出了有可能建設成標準公路的若干條道路的成本,求使每個村落都有公路連通所需要的最低成本。
輸入格式:
輸入數據包括城鎮數目正整數N(≤1000)和候選道路數目M(≤3N);隨後的M行對應M條道路,每行給出3個正整數,分別是該條道路直接連通的兩個城鎮的編號以及該道路改建的預算成本。爲簡單起見,城鎮從1到N編號。
輸出格式:
輸出村村通需要的最低成本。如果輸入數據不足以保證暢通,則輸出−1,表示需要建設更多公路。
輸入樣例:
6 15
1 2 5
1 3 3
1 4 7
1 5 4
1 6 2
2 3 4
2 4 6
2 5 2
2 6 6
3 4 6
3 5 1
3 6 1
4 5 10
4 6 8
5 6 3
輸出樣例:
12
最小生成樹
代碼:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAX = 1009;
struct edge
{
int u, v, cost;
};
edge road[3 * MAX];
int N, M;
int father[MAX];
bool cmp(edge a, edge b)
{
return a.cost < b.cost;
}
int find_father(int x)
{
if( x != father[x] )
{
father[x] = find_father(father[x]);
}
return father[x];
}
bool merge_road(int x, int y)
{
int father1 = find_father(x);
int father2 = find_father(y);
if( father1 != father2 )
{
father[father1] = father2;
return true;
}
return false;
}
int main()
{
scanf("%d%d", &N, &M);
for(int i = 1; i <= N; i++)
father[i] = i;
for( int i = 0; i < M; i++ )
{
scanf("%d%d%d", &road[i].u, &road[i].v, &road[i].cost);
}
sort(road, road + M, cmp);
int ans = 0, cnt = 0;
for( int i = 0; i < M; i++ )
{
if( merge_road(road[i].u, road[i].v) )
{
ans += road[i].cost;
cnt++;
}
}
if(cnt == N - 1)
printf("%d\n", ans);
else
printf("-1\n");
return 0;
}