AcWing 858. Prim算法求最小生成树
原题链接
简单
作者:
sky-koi
,
2024-12-12 10:13:48
,
所有人可见
,
阅读 1
/*
* @Author: Wangshuo Tau
* @Date: 2024-12-12 10:02:59
* @LastEditTime: 2024-12-12 10:09:58
* @Description:
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 510, INF = 0x3f3f3f3f;
struct edge {
int v, w;
};
vector<edge> e[N];
int d[N];
bool vis[N];
int ans, cnt;
int n, m;
bool prim(int s) {
for (int i = 0; i <= n; i++) {
d[i] = INF;
}
d[s] = 0;
for (int i = 1; i <= n; i++) {
int u = 0;
for (int j = 1; j <= n; j++) {
if (!vis[j] && d[j] < d[u])
u = j;
}
if (d[u] == INF) return false;
vis[u] = 1;
ans += d[u];
cnt++;
for (auto ed : e[u]) {
int v = ed.v, w = ed.w;
if (d[v] > w) {
d[v] = w;
}
}
}
return cnt == n;
}
int main() {
scanf("%d%d", &n, &m);
int u, v, w;
while (m--) {
scanf("%d%d%d", &u, &v, &w);
e[u].push_back({v, w});
e[v].push_back({u, w});
}
if (prim(1))
cout << ans << endl;
else
cout << "impossible" << endl;
return 0;
}