#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 1000, INF = 10000010;
int n, m, k; int dist[N]; int g[N][N]; bool str[N];
int prim()
{
int res = 0;
for (int i = 0; i < n; i++)
{
int t = -1;
for (int j = 1; j < n; j++)
{
if (!str[j] && (t == -1 || dist[j] < dist[t]))
t = j;
}
str[t] = true;
if (i && dist[t] == INF)return INF;
if (i)res += dist[t];
for (int j = 1; j < n; j++)
dist[j] = min(dist[j], g[t][j]);
}
return res;
}
int main()
{
memset(g, INF, sizeof g);
cin >> n >> m;
while (m--)
{
int a, b,c;
cin >> a >> b>>c;
g[a][b] = g[b][a] = min(g[a][b],c);
}
int t = prim();
cout << t;
}
prim算法
最新推荐文章于 2024-08-20 17:09:37 发布