Hướng giải của Bình xăng giới hạ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.
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ả:
Lời giải
Dijkstra với trạng thái dist[u][fuel] = độ dài địa lý ngắn nhất đến u với bình 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 d;
int u, fuel;
bool operator>(const State& other) const {
return d > other.d;
}
};
long long dist[1005][105];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, m, f, s, t;
if (!(cin >> n >> m >> f >> s >> t)) return 0;
vector<int> has_station(n + 1);
for (int i = 1; i <= n; i++) cin >> has_station[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});
adj[v].push_back({u, w});
}
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= f; j++) {
dist[i][j] = INF;
}
}
priority_queue<State, vector<State>, greater<State>> pq;
// We start at s. If s has a station, we start with full fuel f, else we start with 0?
// Wait, the description says "Ban đầu tại S, đổ đầy bình xăng" or we start with full fuel.
// Let's assume we start with full fuel F at s.
dist[s][f] = 0;
pq.push({0, s, f});
while (!pq.empty()) {
auto [d, u, fuel] = pq.top();
pq.pop();
if (d > dist[u][fuel]) continue;
int current_fuel = fuel;
if (has_station[u]) {
current_fuel = f;
dist[u][f] = min(dist[u][f], d);
}
for (auto& edge : adj[u]) {
int v = edge.first;
int w = edge.second;
if (current_fuel >= w) {
if (d + w < dist[v][current_fuel - w]) {
dist[v][current_fuel - w] = d + w;
pq.push({dist[v][current_fuel - w], v, current_fuel - w});
}
}
}
}
long long ans = INF;
for (int j = 0; j <= f; j++) ans = min(ans, dist[t][j]);
cout << (ans == INF ? -1 : ans) << "\n";
return 0;
}
Nhận xét