跳到正文

题解

最小乘积路 题解

DrAlfred约 3 分钟
原文
文章信息与版本

文章信息

发布
2024年7月23日
收录
2025年12月12日
更新
2026年11月10日
篇幅
约 3 分钟

版本

  1. v1当前

摘要:数学,图论,最短路

传送门:https://marsoj.cn/p/P2334

题意

求 11 到 nn 的路径的点权成绩的最小值对 99879987 取模的值。

分析思路

直接用高精度跑乘积的 Dijkstra 会 MLE,考虑将乘法转换为加法。注意到 log⁡(a)+log⁡(b)=log⁡(ab)\log (a) + \log (b) = \log (ab)。我们可以使用 log⁡\log 边权跑和的最短路,用 pre 数组记录路径,再从终点回溯即可。

代码

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
struct Edge {
    int to, w;
} pre[N];
struct Node {
    int pos;
    double w;
    inline bool operator<(const Node &x) const {
        return w > x.w;
    }
} last;
double dis[N];
vector<Edge> G[N];
int n, m, u, v, w;
priority_queue<Node> heap;
inline void optimizeIO(void) {
    ios::sync_with_stdio(false);
    cin.tie(NULL), cout.tie(NULL);
}
int main(int argc, char const *argv[]) {
    optimizeIO(), cin >> n >> m;
    for (int i = 2; i <= n; i++) dis[i] = 1e9;
    for (int i = 1; i <= m; i++) {
        cin >> u >> v >> w;
        G[u].push_back({v, w});
    }
    heap.push({1, 0});
    while (!heap.empty()) {
        last = heap.top(), heap.pop();
        if (dis[last.pos] != last.w) {
            continue;
        }
        for (auto edge : G[last.pos]) {
            if (dis[edge.to] > last.w + std::log(edge.w)) {
                dis[edge.to] = last.w + std::log(edge.w);
                heap.push({edge.to, dis[edge.to]});
                pre[edge.to] = {last.pos, edge.w};
            }
        }
    }
    int ans = 1;
    for (int i = n; i != 1; i = pre[i].to) {
        ans = pre[i].w % 9987 * ans % 9987;
    }
    cout << ans << endl;
    return 0;
}
原文