From b39982830099c5235d6c7f2a7cd1363d82d96ec5 Mon Sep 17 00:00:00 2001 From: Ren Baoshuo Date: Tue, 10 Aug 2021 10:53:07 +0800 Subject: [PATCH] =?UTF-8?q?858.=20Prim=E7=AE=97=E6=B3=95=E6=B1=82=E6=9C=80?= =?UTF-8?q?=E5=B0=8F=E7=94=9F=E6=88=90=E6=A0=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://www.acwing.com/problem/content/submission/code_detail/7021576/ --- AcWing/858/858.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 AcWing/858/858.cpp diff --git a/AcWing/858/858.cpp b/AcWing/858/858.cpp new file mode 100644 index 00000000..7c46a196 --- /dev/null +++ b/AcWing/858/858.cpp @@ -0,0 +1,42 @@ +#include + +using namespace std; + +int n, m, u, v, w, g[505][505], dist[505]; +bool vis[505]; + +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 (!vis[j] && (t == -1 || dist[j] < dist[t])) { + t = j; + } + } + if (i && dist[t] == 0x3f3f3f3f) return 0x3f3f3f3f; + if (i) res += dist[t]; + for (int j = 1; j <= n; j++) { + dist[j] = min(dist[j], g[t][j]); + } + vis[t] = true; + } + return res; +} + +int main() { + cin >> n >> m; + memset(g, 0x3f, sizeof(g)); + for (int i = 0; i < m; i++) { + cin >> u >> v >> w; + g[u][v] = g[v][u] = min(g[u][v], w); + } + int ans = prim(); + if (ans == 0x3f3f3f3f) { + cout << "impossible" << endl; + } else { + cout << ans << endl; + } + return 0; +}