【题解】P4009 汽车加油行驶问题

题意

给定整数 \(n,k,a,b,c\) 和一个 \(n\times n\) 的 \(0/1\) 矩阵 \(S\)。矩阵中 \(S_{i,j} = 1\) 表示有油库,\(S_{i,j} = 0\) 表示无油库。保证 \(S_{1,1} = S_{n,n} = 0\)。

汽车从起点 \((1,1)\) 行驶到终点 \((n,n)\),行驶过程中遵守如下规则:

  • 汽车油箱容量为 \(k\) 单位,每走一格消耗 \(1\) 单位的油。
  • 若汽车向右或向下移动不需要费用,但是向左和向上需要支付 \(b\)。
  • 汽车遇到油库时必须加满油并支付 \(c\)。
  • 如果需要,可以增设油库,代价为 \(a\)(不包括加油费用)。

数据范围: \(2\le n \le 100\),\(2\le k \le 10\)

思路

考虑以油量建立 \(k+1\) 个图,则当油量为 \(oil\) 时行驶到 \((x,y)\) 的节点编号为

\[get(x,y,oil) = oil \times n^2 + (x-1)n + y \]

然后根据题意模拟建边,最后以 \(get(1,1,k)\) 为起点跑单源最短路,最终答案为

\[\min_{0\le t \le k} dist_{get(n,n,t)} \]

代码

#include <bits/stdc++.h>
#define int long long
using namespace std;

const int MAXN = 105;
const int MAXV = 2e5 + 5;
int n, k, a, b, c;
int mp[MAXN][MAXN], vis[MAXV], dist[MAXV];
vector<pair<int, int>> G[MAXV];

int get(int x, int y, int oil) {
    return oil * n * n + (x - 1) * n + y;
}

void Dijkstra(int start) {
    memset(dist, 0x3f, sizeof dist);
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
    q.push({0, start}), dist[start] = 0;
    while (!q.empty()) {
        auto [dis, cur] = q.top();
        q.pop();
        if (vis[cur]) continue;
        vis[cur] = 1;
        for (auto [nxt, w] : G[cur])
            if (dist[nxt] > dist[cur] + w) {
                dist[nxt] = dist[cur] + w;
                q.push({dist[nxt], nxt});
            }
    }
}

signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    //	freopen("file.in","r",stdin);
    //	freopen("file.out","w",stdout);
    cin >> n >> k >> a >> b >> c;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++) cin >> mp[i][j];

    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++) {
            if (mp[i][j] == 0) {
                for (int t = 0; t <= k; t++) G[get(i, j, t)].push_back({get(i, j, k), a + c});
                for (int t = 1; t <= k; t++) {
                    if (i >= 2) G[get(i, j, t)].push_back({get(i - 1, j, t - 1), b});
                    if (j >= 2) G[get(i, j, t)].push_back({get(i, j - 1, t - 1), b});
                    if (i < n) G[get(i, j, t)].push_back({get(i + 1, j, t - 1), 0});
                    if (j < n) G[get(i, j, t)].push_back({get(i, j + 1, t - 1), 0});
                }
            } else {
                for (int t = 0; t <= k; t++) G[get(i, j, t)].push_back({get(i, j, k), a});
                if (i >= 2) G[get(i, j, k)].push_back({get(i - 1, j, k - 1), b});
                if (j >= 2) G[get(i, j, k)].push_back({get(i, j - 1, k - 1), b});
                if (i < n) G[get(i, j, k)].push_back({get(i + 1, j, k - 1), 0});
                if (j < n) G[get(i, j, k)].push_back({get(i, j + 1, k - 1), 0});
            }
        }
    Dijkstra(get(1, 1, k));
    int ans = 1145141919810;
    for (int t = 0; t <= k; t++) ans = min(ans, dist[get(n, n, t)]);
    cout << ans << "\n";
    return 0;
}
posted @ 2026-09-25 11:41  C0nfidence  阅读(26)  评论(0)    收藏  举报