题解:P10917 电王的传送迷宫

· · 题解

题目思路

不难看出,对于每一次决定,要么去走传送门,要么直接走到终点。

那么先计算每个点能走到最近的传送入口的距离,因为任意的传送入口都可以使用,只是传送地点不同,故把所有传送入口当作起点,跑多源 bfs 解决。

再求出传送 i - 1 后到达的传送出口前往最近的传送入口的最短距离,只需要将传送 i - 1 次的最短距离加上前往最近的传送入口的最短距离就能算出来,可以用递推解决。

接着,把这 q 个出口当作起点,再跑一次多源 bfs 解决,注意这里要用优先队列。

AC Code

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

const int N = 1005, P = 1000 * 1000 + 5;
const int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0};

struct Grid {
    int x = -1, y = -1;
};

struct Queue {
    int x, y, dis;
    bool operator < (const Queue &a) const {
        return dis > a.dis;
    }
};

struct Node {
    char map;
    int cdis = -1, dis = -1;
};

int n, m, opt, sx, sy, tx = -1, ty = -1, p, k;
vector<int> f(P, -1);
vector<Grid> S(P), T(P);
vector<vector<Node> > g(N, vector<Node>(N));
queue<Grid> q;
priority_queue<Queue> qq;

signed main() {
    ios::sync_with_stdio(false), cin.tie(nullptr);
    cin >> opt >> n >> m;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            cin >> g[i][j].map;
    cin >> sx >> sy >> p >> k; if (opt) cin >> tx >> ty;
    for (int i = 1; i <= p; i++) {
        cin >> S[i].x >> S[i].y;
        g[S[i].x][S[i].y].cdis = 0;
        q.push(S[i]);
    }
    for (int i = 1; i <= k; i++)
        cin >> T[i].x >> T[i].y;
    while (!q.empty()) {
        auto [x, y] = q.front(); q.pop();
        for (int w = 0; w < 4; w++) {
            int i = x + dx[w], j = y + dy[w];
            if (i >= 1 && i <= n && j >= 1 && j <= m && g[i][j].map == '.' && g[i][j].cdis == -1) {
                g[i][j].cdis = g[x][y].cdis + 1;
                q.push({i, j});
            }
        }
    }
    f[1] = g[sx][sy].cdis;
    for (int i = 2; i <= k; i++) {
        if (g[T[i - 1].x][T[i - 1].y].cdis == -1 || f[i - 1] == -1)
            f[i] = -1;
        else
            f[i] = f[i - 1] + g[T[i - 1].x][T[i - 1].y].cdis;
    }
    g[sx][sy].dis = 0; qq.push({sx, sy, 0});
    for (int i = 1; i <= k; i++)
        if (f[i] != -1 && (g[T[i].x][T[i].y].dis == -1 || f[i] < g[T[i].x][T[i].y].dis))
            qq.push({T[i].x, T[i].y, g[T[i].x][T[i].y].dis = f[i]});
    while (!qq.empty()) {
        auto [x, y, disdis] = qq.top(); qq.pop();
        if (disdis != g[x][y].dis) continue;
        for (int w = 0; w < 4; w++) {
            int i = x + dx[w], j = y + dy[w];
            if (i >= 1 && i <= n && j >= 1 && j <= m && g[i][j].map == '.' && (g[i][j].dis > g[x][y].dis + 1 || g[i][j].dis == -1))
                qq.push({i, j, g[i][j].dis = g[x][y].dis + 1});
        }
    }
    if (opt)
        cout << g[tx][ty].dis << '\n';
    else {
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++)
                cout << g[i][j].dis << ' ';
            cout << '\n';
        }
    }
    return 0;
}