AcWing 858. Prim算法求最小生成树
原题链接
简单
作者:
oyel
,
2020-09-11 14:25:29
,
所有人可见
,
阅读 423
# include <iostream>
# include <cstring>
using namespace std;
const int N = 510;
int g[N][N];
int dist[N];
bool st[N];
int main(){
int n, m;
cin >> n >> m;
memset(g, 0x3f, sizeof g);
while(m--){
int x, y, z;
cin >> x>> y >> z;
g[x][y] = g[y][x] = min(g[x][y], z);
}
int res = 0;
memset(dist, 0x3f, sizeof dist);
dist[1] = 0; // 1号元素
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 (dist[t] == 0x3f3f3f3f){
res = 0x3f3f3f3f;
break;
}
st[t] = true;
res += dist[t];
for (int j=1; j<=n; j++){
if (!st[j])
dist[j] = min(dist[j], g[t][j]);
}
}
if (res == 0x3f3f3f3f) cout << "impossible" << endl;
else cout << res << endl;
return 0;
}