From cf1446b12ccc188ec0d41b9347852dae93d9f39f Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Fri, 28 Oct 2022 22:15:17 +0800 Subject: [PATCH] =?UTF-8?q?P3371=20=E3=80=90=E6=A8=A1=E6=9D=BF=E3=80=91?= =?UTF-8?q?=E5=8D=95=E6=BA=90=E6=9C=80=E7=9F=AD=E8=B7=AF=E5=BE=84=EF=BC=88?= =?UTF-8?q?=E5=BC=B1=E5=8C=96=E7=89=88=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://www.luogu.com.cn/record/91965144 --- Luogu/P3371/P3371.cpp | 74 +++++++++++++++++++++++++++++-------------- 1 file changed, 51 insertions(+), 23 deletions(-) diff --git a/Luogu/P3371/P3371.cpp b/Luogu/P3371/P3371.cpp index 682264a3..a1bb9119 100644 --- a/Luogu/P3371/P3371.cpp +++ b/Luogu/P3371/P3371.cpp @@ -1,43 +1,71 @@ -#include +#include +#include +#include +#include +#include +#include -using namespace std; +using std::cin; +using std::cout; +const char endl = '\n'; -int n, m, s, u, v, w, dist[200005]; -vector> g[200005]; -bool st[200005]; +const int N = 1e5 + 5; -void dijkstra() { - memset(dist, 0x3f, sizeof(dist)); +int n, m, s; +long long dist[N]; +std::vector> g[N]; +bool vis[N]; + +void spfa() { + std::fill_n(dist, N, std::numeric_limits::max()); + + std::queue q; + + q.emplace(s); dist[s] = 0; - priority_queue, vector>, greater>> q; - q.push(make_pair(0, s)); + vis[s] = true; + while (!q.empty()) { - auto t = q.top(); + int u = q.front(); q.pop(); - int tw = t.second; - int td = t.first; - if (st[tw]) continue; - for (auto i : g[tw]) { - int j = i.first; - if (dist[j] > td + i.second) { - dist[j] = td + i.second; - q.push(make_pair(dist[j], j)); + + vis[u] = false; + + for (auto e : g[u]) { + int v = e.first; + long long w = e.second; + + if (dist[v] > dist[u] + w) { + dist[v] = dist[u] + w; + + if (!vis[v]) { + vis[v] = true; + q.emplace(v); + } } } - st[tw] = true; } } int main() { + std::ios::sync_with_stdio(false); + cin.tie(nullptr); + cin >> n >> m >> s; - for (int i = 1; i <= m; i++) { + + for (int i = 1, u, v, w; i <= m; i++) { cin >> u >> v >> w; - g[u].push_back(make_pair(v, w)); + + g[u].emplace_back(v, w); } - dijkstra(); + + spfa(); + for (int i = 1; i <= n; i++) { - cout << (dist[i] == 0x3f3f3f3f ? INT_MAX : dist[i]) << ' '; + cout << dist[i] << ' '; } + cout << endl; + return 0; }