跳转至

概率最大的路径⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
public:
    double maxProbability(int n, vector<vector<int>>& edges, vector<double>& succProb, int start_node, int end_node) {
        using PDI = pair<double, int>;
        vector<vector<PDI>> graph(n);
        for (int i = 0; i < edges.size(); i++) {
            graph[edges[i][0]].emplace_back(succProb[i], edges[i][1]);
            graph[edges[i][1]].emplace_back(succProb[i], edges[i][0]);
        }

        priority_queue<PDI> que;
        que.emplace(1.0, start_node);

        vector<double> prob(n, 0.0);
        prob[start_node] = 1.0;

        while (!que.empty()) {
            auto [currentProb, node] = que.top();
            que.pop();

            if (currentProb < prob[node]) continue;

            for (auto& [nextProb, nextNode] : graph[node]) {
                if (prob[nextNode] < prob[node] * nextProb) {
                    prob[nextNode] = prob[node] * nextProb;
                    que.emplace(prob[nextNode], nextNode);
                }
            }
        }

        return prob[end_node];
    }
};