模板题。
方法一:prim
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1010, INF = 0x3f3f3f3f;
int n, m;
int g[N][N], dist[N];
bool st[N];
int prim()
{
int res = 0;
memset(dist, 0x3f, sizeof(dist));
for (int i = 0; i < n; i ++)
{
int t = -1;
for (int j = 1; j <= n; j ++)
if (!st[j] && (t == -1 || (dist[t] > dist[j])))
t = j;
if (i && dist[t] == INF) return INF;
if (i) res += dist[t];
st[t] = true;
for (int i = 1; i <= n; i ++) dist[i] = min(dist[i], g[t][i]);
}
return res;
}
int main()
{
cin >> n >> m;
memset(g, 0x3f, sizeof(g));
while (m --)
{
int a, b, c;
cin >> a >> b >> c;
g[a][b] = g[b][a] = min(g[a][b], c);
}
int res = prim();
if (res == INF) puts("-1");
else cout << res << endl;
return 0;
}
方法二:kruskal
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010, M = 3 * N, INF = 0x3f3f3f3f;
int n, m;
int p[N];
struct Edge
{
int a, b, w;
bool operator< (const Edge& t) const
{
return w < t.w;
<