Dijkstra 优先队列优化

/*
建图用的邻接表,复杂度O(E*logE)
*/

struct pnode {
    int num;
    int len;

    pnode() {}
    pnode(int a, int b) : num(a), len(b) {}
    bool operator < (const pnode tmp) const {
        return len > tmp.len;
    }
};

int dis[N];
bool vis[N];
int n;

void bfs(int s) {
    priority_queue q;
    q.push(pnode(s, 0));
    pnode u;
    int v, i, res = inf;
    for(i = 0; i <= n; ++i) dis[i] = inf, vis[i] = false;
    dis[s] = 0;

    while(!q.empty()) {
        u = q.top(); q.pop();
        if(u.len != dis[u.num]) continue;
        if(vis[u.num])  continue;
        vis[u.num] = true;

        for(i = head[u.num]; i != -1; i = g[i].next) {
            v = g[i].to;
            if(dis[v] > u.len + g[i].val) {
                dis[v] = u.len + g[i].val;
                q.push(pnode(v, dis[v]));
            }
        }
    }
}

你可能感兴趣的:(Dijkstra 优先队列优化)