LeetCode 1514. 概率最大的路径 (单源最短路径、迪杰斯塔拉算法)

概率最大的路径
这里的最大概率之积和最短路的问题有相似之处,因为都是之后出现的边会减小概率(或者增大路径长度)

class Solution {
public:
    struct Edge{
        int to;
        double val;
        Edge(int to,double val):to(to),val(val){}
    };

    double ans = 0;
    vector<Edge> es;
    vector<int> g[(int)1e4+10];
    int vis[10010] = {0};
    double d[10010] = {0};

    double maxProbability(int n, vector<vector<int>>& edges, vector<double>& su, int start, int end) {
        for(int i=0;i<edges.size();i++){
            vector<int> &e = edges[i];
            es.push_back(Edge(e[1],su[i]));
            g[e[0]].push_back(es.size()-1);
            es.push_back(Edge(e[0],su[i]));
            g[e[1]].push_back(es.size()-1);
        }
        dijk(start,end);
        return d[end];
    }

    void dijk(int start, int end) {
        typedef pair<double,int> P;
        priority_queue<P> pq;
        pq.push(make_pair(1.0,start));
        d[start] = 1;
        while(pq.size()) {
            P p = pq.top();
            pq.pop();
            int x = p.second;
            if(vis[x]){
                continue;
            }
            vis[x] = 1;
            for(int idx:g[x]){
                int y = es[idx].to;
                double val = es[idx].val;
                if(d[y]<val*d[x]){
                    d[y] = val*d[x];
                    pq.push(make_pair(d[y],y));
                }
            }
        }
    }

};

你可能感兴趣的:(LeetCode,#,LC图论)