08-图7 公路村村通 (30 point(s))
现有村落间道路的统计数据表中,列出了有可能建设成标准公路的若干条道路的成本,求使每个村落都有公路连通所需要的最低成本。
输入格式:
输入数据包括城镇数目正整数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
这里使用一个简单的没有优化的并查集,以及Kruskal算法
#include <iostream>
#include <algorithm>
using namespace std;
const int INF = 10000;
const int N = 5000;
// 边的信息
struct Edge
{
int a, b, v;
bool operator< (const Edge &W) const
{
return v < W.v;
}
};
Edge edge[N];
int father[N];
int n, m;
void ReadGraph()
{
scanf("%d %d", &n, &m);
int V1,V2,weight;
for (int i = 0; i < m; i++) {
scanf("%d %d %d", &V1, &V2, &weight);
edge[i].a = V1;
edge[i].b = V2;
edge[i].v = weight;
}
}
// 并查集——寻找当前集合的代表元素
int find(int x)
{
if (father[x] != x) father[x] = find(father[x]);
return father[x];
}
// 所有边存储在 Edge edges[M];
// 函数返回最小生成树中所有边的总长度
int Kruskal(int &count)
{
int res = 0;
// 初始化并查集代表元素
for (int i = 1; i <= n; i++) father[i] = i;
sort(edge, edge + m);
for (int i = 0; i < m; i++)
{
int a = edge[i].a, b = edge[i].b;
if (find(a) != find(b))
{
count++;
res += edge[i].v;
father[find(a)] = find(b);
}
}
return res;
}
int main()
{
ReadGraph();
int count = 0;
int res = Kruskal(count);
if (count == n - 1)
cout << res << endl;
else
cout << -1 << endl;
}