Hướng giải của Trạm sạc xe điện


Nhớ rằng hướng dẫn giải này chỉ nên sử dụng khi bế tắc, và tuyệt đối không nên sao chép mã nguồn kèm theo. Hãy tôn trọng tác giả bài tập và người viết hướng dẫn giải.
Nộp mã nguồn lời giải chính thức trước khi giải bài tập đó có thể khiến bạn bị ban.

Tác giả: kienadmin

Lời giải

Dijkstra với trạng thái dist[u][fuel] = chi phí tối thiểu tới u với dung lượng xăng còn lại.

Mã nguồn C++ mẫu
#include <bits/stdc++.h>
using namespace std;

const long long INF = 1e18;

struct State {
    long long cost;
    int u, fuel;
    bool operator>(const State& other) const {
        return cost > other.cost;
    }
};

long long dist[1005][105];

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n, m, c, s, t;
    if (!(cin >> n >> m >> c >> s >> t)) return 0;
    vector<long long> p(n + 1);
    for (int i = 1; i <= n; i++) cin >> p[i];
    vector<vector<pair<int, int>>> adj(n + 1);
    for (int i = 0; i < m; i++) {
        int u, v, w;
        cin >> u >> v >> w;
        adj[u].push_back({v, w});
    }

    for (int i = 1; i <= n; i++) {
        for (int f = 0; f <= c; f++) {
            dist[i][f] = INF;
        }
    }

    priority_queue<State, vector<State>, greater<State>> pq;
    dist[s][0] = 0;
    pq.push({0, s, 0});

    while (!pq.empty()) {
        auto [cost, u, fuel] = pq.top();
        pq.pop();
        if (cost > dist[u][fuel]) continue;

        // Option 1: Buy 1 unit of fuel at u if there is a charging station
        if (p[u] > 0 && fuel < c) {
            if (cost + p[u] < dist[u][fuel + 1]) {
                dist[u][fuel + 1] = cost + p[u];
                pq.push({dist[u][fuel + 1], u, fuel + 1});
            }
        }

        // Option 2: Go to adjacent nodes
        for (auto& edge : adj[u]) {
            int v = edge.first;
            int w = edge.second;
            if (fuel >= w) {
                if (cost < dist[v][fuel - w]) {
                    dist[v][fuel - w] = cost;
                    pq.push({dist[v][fuel - w], v, fuel - w});
                }
            }
        }
    }
    long long ans = INF;
    for (int f = 0; f <= c; f++) {
        ans = min(ans, dist[t][f]);
    }
    cout << (ans == INF ? -1 : ans) << "\n";
    return 0;
}

Nhận xét

Không có ý kiến tại thời điểm này.