Editorial for Robot bảo dưỡng mạng


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Author: hazzu

#include <bits/stdc++.h>
#define taskname "olp0052"
using namespace std;

typedef long long ll;
typedef pair<ll, ll> ii;
const ll inf = 1e18;

void Input() {
    ios_base::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    if (fopen(taskname".inp", "r")) {
        freopen(taskname".inp", "r", stdin);
        freopen(taskname".out", "w", stdout);
    }
}

void Solve() {
    int n, m; cin >> n >> m;
    vector<vector<ii>> adj(n + 1);
    for (int i = 1; i <= m; i++) {
        int u, v, c; cin >> u >> v >> c;
        adj[u].push_back({v, c});
        adj[v].push_back({u, c});
    }

    auto dijkstra = [&](int s, vector<ll> &dist) {
        vector<bool> visited(n + 1, false);
        dist.assign(n + 1, inf);
        priority_queue<ii> PQ;

        dist[s] = 0;
        PQ.push({dist[s], s});

        while (!PQ.empty()) {
            int u = PQ.top().second; PQ.pop();
            if (visited[u]) continue;
            visited[u] = true;

            for (auto [v, c]: adj[u]) 
                if (!visited[v] && dist[v] > dist[u] + c) {
                    dist[v] = dist[u] + c;
                    PQ.push({-dist[v], v});
                }
        }
    };

    int s1, s2; cin >> s1 >> s2;
    vector<ll> dist1, dist2;
    dijkstra(s1, dist1);
    dijkstra(s2, dist2);

    ll ans = inf, dfsTime = 0;
    vector<int> low(n + 1, 0), num(n + 1, 0);
    function<void(int, int)> dfs = [&](int u, int p) {
        low[u] = num[u] = ++dfsTime;
        for (auto [v, c]: adj[u]) {
            if (v == p) continue;
            if (num[v]) low[u] = min(low[u], num[v]);
            else {
                dfs(v, u);
                low[u] = min(low[u], low[v]);

                if (low[v] >= num[v]) {
                    ans = min(ans, max(dist1[v], dist2[u]));
                    ans = min(ans, max(dist2[v], dist1[u]));
                }
            }
        }
    };

    for (int i = 1; i <= n; i++)
        if (!num[i]) dfs(i, i);
    cout << ans;
}

int main(){
    Input();
    Solve();
    return 0;
}

Comments