代码思路来自AcWing
What is the Min spaning tree ? -----》Click this to know the answer
测试样例
Input:
4 5
1 2 1
1 3 2
1 4 3
2 3 2
3 4 4
Output:
6
The Code:
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
const int N = 520;
const int INF = 0x3f3f3f3f;
int g[N][N];
int dist[N];
int st[N];
int n, m;
int prim()
{
memset(dist, 0x3f, sizeof dist);
int res = 0;
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;
st[t] = true;
if(dist[t] == INF && i) return INF;
if(i) res += dist[t];
for (int j = 1; j <= n; ++j) dist[j] = min(g[t][j], dist[j]);
}
return res;
}
int main()
{
memset(g, 0x3f, sizeof g);
scanf("%d%d",&n, &m);
for (int i = 0; i < m; ++i)
{
int a, b, c;
scanf("%d%d%d",&a, &b, &c);
g[a][b] = g[b][a] = min(g[a][b], c);
}
int t = prim();
if(t == INF) cout << "impossible" << endl;
else cout << t << endl ;
return 0;
}