From 8d26140581d1981bceef13472f8cb208aff3a6e6 Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Sat, 1 Jan 2022 20:40:59 +0800 Subject: [PATCH] =?UTF-8?q?P2169=20=E6=AD=A3=E5=88=99=E8=A1=A8=E8=BE=BE?= =?UTF-8?q?=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit R66112607 --- Luogu/P2169/P2169.cpp | 92 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 Luogu/P2169/P2169.cpp diff --git a/Luogu/P2169/P2169.cpp b/Luogu/P2169/P2169.cpp new file mode 100644 index 00000000..7798ef2b --- /dev/null +++ b/Luogu/P2169/P2169.cpp @@ -0,0 +1,92 @@ +#include +#include +#include +#include +#include + +using std::cin; +using std::cout; +using std::endl; + +// Limits +const int N = 200005; + +// Graphs +int w[N]; +std::vector> g[N]; + +// Tarjan +int cnt, dfn[N], low[N]; +int scc_cnt, id[N]; +std::stack st; +bool vis[N]; + +void tarjan(int u) { + dfn[u] = low[u] = ++cnt; + st.push(u); + vis[u] = true; + for (auto v : g[u]) { + if (!dfn[v.first]) { + tarjan(v.first); + low[u] = std::min(low[u], low[v.first]); + } else if (vis[v.first]) { + low[u] = std::min(low[u], dfn[v.first]); + } + } + if (low[u] == dfn[u]) { + scc_cnt++; + int v; + do { + v = st.top(); + st.pop(); + vis[v] = false; + id[v] = scc_cnt; + } while (v != u); + } +} + +// Shortest Path +int dist[N]; + +void spfa() { + std::fill(dist, dist + N, 0x3f3f3f3f); + std::fill(vis, vis + N, false); + std::queue q; + q.push(1); + dist[1] = 0; + vis[1] = true; + while (!q.empty()) { + auto u = q.front(); + q.pop(); + vis[u] = 0; + for (auto v : g[u]) { + int w = v.second; + if (id[u] == id[v.first]) w = 0; + if (dist[v.first] > dist[u] + w) { + dist[v.first] = dist[u] + w; + if (!vis[v.first]) { + q.push(v.first); + vis[v.first] = true; + } + } + } + } +} + +int main() { + int n, m; + cin >> n >> m; + for (int i = 1; i <= m; i++) { + int u, v, w; + cin >> u >> v >> w; + g[u].push_back(std::make_pair(v, w)); + } + for (int i = 1; i <= n; i++) { + if (!dfn[i]) { + tarjan(i); + } + } + spfa(); + cout << dist[n] << endl; + return 0; +}