题解:P11898 移动迷宫

· · 题解

这道题很显然吧。

我们分析一下 t 值的变换:

t \Rightarrow \frac{1}{1-t} \Rightarrow \frac{t - 1}{t} \Rightarrow t.

容易发现这是一个循环节为 3 的变换过程,那么我们可以令 f_{i, 0/1/2} 表示从 1 到 i,且当前状态为 0/1/2 的最短路即可,时间复杂度 \mathcal{O}(n \log m)。

代码如下:

#define MULTI_TEST 0
#define int long long
struct Node {
    int v;
    int c[3];
};
int32_t main() {
#if MULTI_TEST == 1
#else
    int n, m;
    std::cin >> n >> m;
    std::vector<std::vector<Node>> adj(n + 1);
    for (int i = 0; i < m; ++i) {
        int x, y, w;
        std::cin >> x >> y >> w;
        int c0 = (LL)Z(w);
        int c1 = (LL)(Z(1) / Z(1 - w));
        int c2 = (LL)(Z(w - 1) / Z(w));
        adj[x].pb(Node{ y,{c0,c1,c2} });
        adj[y].pb(Node{ x,{c0,c1,c2} });
    }
    std::vector<std::vector<int>> dist(n + 1, std::vector<int>(3, 1e18));
    dist[1][0] = 0;
    using qwq = std::tuple<LL, int, int>;
    std::priority_queue<qwq, std::vector<qwq>, std::greater<qwq>> pq;
    pq.push({ 0,1,0 });
    while (!pq.empty()) {
        auto [d, x, r] = pq.top();
        pq.pop();
        if (d != dist[x][r]) continue;
        for (auto& v : adj[x]) {
            int y = v.v, cost = v.c[r];
            if (cost + d < dist[y][(r + 1) % 3]) {
                dist[y][(r + 1) % 3] = cost + d;
                pq.push({ dist[y][(r + 1) % 3], y, (r + 1) % 3 });
            }
        }
    }
    std::cout << std::min({ dist[n][0], dist[n][1], dist[n][2] }) << "\n";
#endif
}