P17639 [ICPC 2019 Yinchuan R] Delivery Route 题解

· · 题解

P17639 [ICPC 2019 Yinchuan R] Delivery Route 题解

题意

给出一张 n 个点的图,其中有 x 张双向边,保证边权非负,有 y 条单向边,边权无约束。求从 s 到各个点的最小距离。

题解

题目保证了有向边不会构成环。所以我们可以考虑无向边先缩点,然后对于构成的有向图进行拓扑排序来求最短路。

这样就做好了。

Code

#include <bits/stdc++.h>
#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
using namespace std;

namespace Lemon {
    const int N = 5e4 + 5;
    const int inf = 0x3f3f3f3f;
    struct node {
        int v, w;
        bool operator<(const node b) const {
            return w > b.w;
        }
    };
    vector<node> g[N];
    bool vis[N];
    int t, r, p, s;
    int cnt;
    int bel[N], ins[N], dis[N];
    vector<int> b[N];
    inline void dfs(int u) {
        vis[u] = 1;
        bel[u] = cnt;
        b[cnt].push_back(u);
        for (auto [v, w] : g[u]) {
            if (vis[v]) continue;
            dfs(v);
        }
    }
    inline void solve() {
        cin >> t >> r >> p >> s;
        for (int i = 1; i <= r; i++) {
            int a, b, c; cin >> a >> b >> c;
            g[a].push_back({ b, c });
            g[b].push_back({ a, c });
        }
        for (int i = 1; i <= t; i++) {
            if (!vis[i]) cnt++, dfs(i);
        }
        for (int i = 1; i <= p; i++) {
            int a, b, c; cin >> a >> b >> c;
            g[a].push_back({ b, c });
            ins[bel[b]]++;
        }
        memset(vis, 0, sizeof(vis));
        memset(dis, 0x7f, sizeof(dis));
        dis[s] = 0;
        queue<int> q;
        q.push(bel[s]);
        for (int i = 1; i <= cnt; i++) {
            if (!ins[i]) q.push(i);
        }
        priority_queue<node> pq;
        while (!q.empty()) {
            int bl = q.front(); q.pop();
            for (auto u : b[bl]) pq.push({ u, dis[u] });
            while (!pq.empty()) {
                int u = pq.top().v; pq.pop();
                if (vis[u]) continue;
                vis[u] = 1;
                for (auto [v, w] : g[u]) {
                    if (dis[v] > dis[u] + w) {
                        dis[v] = dis[u] + w;
                        if (bel[u] == bel[v]) pq.push({ v, dis[v] });
                    }
                    if (bel[u] != bel[v] && (--ins[bel[v]] == 0)) q.push(bel[v]);
                }
            }
        }
        for (int i = 1; i <= t; i++) {
            if (dis[i] > inf) cout << "NO PATH\n";
            else cout << dis[i] << '\n';
        }
    }
}
signed main() {
    IOS;
    int t = 1;
    // cin >> t;
    while (t--) Lemon::solve();
    return 0;
}