DEV Community

Guhan M
Guhan M

Posted on

Flight Discount | CSES - Algoritmit ongelmanratkaisussa

Problem: https://cses.fi/alon/task/1195

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <array>
#include <tuple>

using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, m;
    cin >> n >> m;

    vector<vector<pair<int, long long>>> graph(n + 1);
    for (int i = 0; i < m; i++) {
        int u, v;
        long long w;
        cin >> u >> v >> w;
        graph[u].push_back({v, w});
    }

    const long long INF = 1e18;
    vector<array<long long, 2>> dist(n + 1, {INF, INF});
    dist[1][0] = 0;
    dist[1][1] = 0;

    priority_queue<tuple<long long, int, int>, vector<tuple<long long, int, int>>, greater<>> pq;
    pq.push({0, 1, 0});
    while (!pq.empty()) {
        auto [udist, u, used] = pq.top();
        pq.pop();

        if (udist > dist[u][used]) continue;

        for (auto edge : graph[u]) {
            int v = edge.first;
            long long w = edge.second;

            if (used) {
                if (dist[v][1] > udist + w) {
                    dist[v][1] = udist + w;
                    pq.push({udist + w, v, 1});
                }
            } else {
                if (dist[v][0] > udist + w) {
                    dist[v][0] = udist + w;
                    pq.push({udist + w, v, 0});
                }

                long long appliedDist = udist + w / 2;
                if (dist[v][1] > appliedDist) {
                    dist[v][1] = appliedDist;
                    pq.push({appliedDist, v, 1});
                }
            }
        }
    }

    cout << min(dist[n][0], dist[n][1]) << '\n';
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)