제출 #1350608

#제출 시각아이디문제언어결과실행 시간메모리
1350608amantharathnayakeCommuter Pass (JOI18_commuter_pass)C++20
15 / 100
180 ms22348 KiB
#include <bits/stdc++.h>
using namespace std;

using ll = long long;

vector<ll> diji(int n, int src, int t, vector<vector<pair<ll, ll>>> &adj) {
    priority_queue<pair<ll, ll>, vector<pair<ll, ll>>, greater<pair<ll, ll>>> pq;
    vector<ll> dist(n + 1, 2e18);
    vector<ll> p(n + 1, -1);
    dist[src] = 0;
    pq.push({0, src});

    while (!pq.empty()) {
        ll d = pq.top().first;
        ll u = pq.top().second;
        pq.pop();

        if (dist[u] < d) continue;

        for (auto e : adj[u]) {
            ll v = e.first;
            ll wt = e.second;

            if (dist[v] > d + wt) {
                dist[v] = d + wt;
                p[v] = u;
                pq.push({dist[v], v});
            }
        }
    }

    vector<ll> pa;
    if (dist[t] == 2e18) return pa;
    ll cur = t;
    while (cur != -1) {
        pa.push_back(cur);
        cur = p[cur];
    }

    std::reverse(pa.begin(), pa.end());
    return pa;
}

ll diji2(int n, int src, int t, vector<vector<pair<ll, ll>>> &adj) {
    priority_queue<pair<ll, ll>, vector<pair<ll, ll>>, greater<pair<ll, ll>>> pq;
    vector<ll> dist(n + 1, 2e18);

    dist[src] = 0;
    pq.push({0, src});

    while (!pq.empty()) {
        ll d = pq.top().first;
        ll u = pq.top().second;
        pq.pop();

        if (dist[u] < d) continue;

        for (auto e : adj[u]) {
            ll v = e.first;
            ll wt = e.second;

            if (dist[v] > d + wt) {
                dist[v] = d + wt;
                pq.push({dist[v], v});
            }
        }
    }
    return dist[t];
}

int main() {
    int n, m;
    cin >> n >> m;
    int s, t;
    cin >> s >> t;
    int u, v;
    cin >> u >> v;
    
    vector<vector<pair<ll, ll>>> adj(n + 1);
    for (int i = 0; i < m; i++) {
        int a, b, c;
        cin >> a >> b >> c;
        // Bi-directional: add both ways
        adj[a].push_back({(ll)b, (ll)c});
        adj[b].push_back({(ll)a, (ll)c});
    }

    vector<ll> path = diji(n, s, t, adj);
    
    if (!path.empty()) {
        for (int i = 1; i < (int)path.size(); i++) {
            
            adj[path[i - 1]].push_back({path[i], 0});
            adj[path[i]].push_back({path[i - 1], 0});
        }
    }

    ll result = diji2(n, u, v, adj);
    if (result >= 2e18) cout << -1 << endl;
    else cout << result << endl;

    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...