测试数据:
8 16
4 5 .35
4 7 .37
5 7 .28
0 7 .16
1 5 .32
0 4 .38
2 3 .17
1 7 .19
0 2 .26
1 2 .36
1 3 .29
2 7 .34
6 2 .40
3 6 .52
6 0 .58
6 4 .93
测试结果:
1.81
代码:
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<utility>
#include<functional>
using namespace std;
const int mx = 10005;
typedef pair<double, int> P; ///first是当MST与该点连接时,所连的那条边的长度,second是顶点编号
struct edge
{
double cost;
int to;
edge(double cost = 0.0, int to = 0): cost(cost), to(to) {}
} e;
vector<edge> G[mx];
double disTo[mx]; /// 当MST与点i连接时,所连的那条边的长度
bool vis[mx];
priority_queue<P, vector<P>, greater<P> > pq;
///复杂度:O(ElogV)
double prim()
{
P p;
int v, i;
double sumcost = 0.0;
memset(disTo, 100, sizeof(disTo));
memset(vis, 0, sizeof(vis));
disTo[0] = 0.0;
while (!pq.empty()) pq.pop();
pq.push(P(0.0, 0));/// 从点0开始构造MST
while (!pq.empty())
{
p = pq.top(), pq.pop();
v = p.second; /// v视作e.from
if (vis[v] || p.first > disTo[v]) continue;
vis[v] = true;
sumcost += disTo[v];
for (i = 0; i < G[v].size(); ++i)
{
e = G[v][i]; /// v视作e.from
if (disTo[e.to] > e.cost)
{
disTo[e.to] = e.cost;
pq.push(P(disTo[e.to], e.to));
}
}
}
return sumcost;
}
int main()
{
int n, m, i, a, b;
double cost;
while (~scanf("%d%d", &n, &m))
{
for (i = 0; i < n; ++i) G[i].clear();
while (m--)
{
scanf("%d%d%lf", &a, &b, &cost);
G[a].push_back(edge(cost, b));
G[b].push_back(edge(cost, a));
}
printf("%.2f\n", prim());
}
return 0;
}
O(V^2)复杂度的算法见