From 9764800d02611cb392264556cab34041f373f98a Mon Sep 17 00:00:00 2001 From: Ren Baoshuo Date: Sat, 17 Jul 2021 20:57:19 +0800 Subject: [PATCH] =?UTF-8?q?849.=20Dijkstra=E6=B1=82=E6=9C=80=E7=9F=AD?= =?UTF-8?q?=E8=B7=AF=20I?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://www.acwing.com/problem/content/submission/code_detail/6501777/ --- AcWing/849/849.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 AcWing/849/849.cpp diff --git a/AcWing/849/849.cpp b/AcWing/849/849.cpp new file mode 100644 index 00000000..57b142f3 --- /dev/null +++ b/AcWing/849/849.cpp @@ -0,0 +1,39 @@ +#include + +using namespace std; + +int n, m, x, y, z, g[505][505], dist[505]; +bool st[505]; + +int diskstra() { + memset(dist, 0x3f, sizeof(dist)); + dist[1] = 0; + for (int i = 0; i < n - 1; i++) { + int t = -1; + for (int j = 1; j <= n; j++) { + if (!st[j] && (t == -1 || dist[t] > dist[j])) { + t = j; + } + } + for (int j = 1; j <= n; j++) { + dist[j] = min(dist[j], dist[t] + g[t][j]); + } + st[t] = true; + } + return dist[n] == 0x3f3f3f3f ? -1 : dist[n]; +} + +int main() { + cin >> n >> m; + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= n; j++) { + g[i][j] = i == j ? 0 : 0x3f3f3f3f; + } + } + for (int i = 1; i <= m; i++) { + cin >> x >> y >> z; + g[x][y] = min(g[x][y], z); + } + cout << diskstra() << endl; + return 0; +}