题目描述:
现有村落间道路的统计数据表中,列出了有可能建设成标准公路的若干条道路的成本,求使每个村落都有公路连通所需要的最低成本。
输入格式:
输入数据包括城镇数目正整数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;
}