dijkstra完整模板

来源:互联网 发布:kendalltau python 编辑:程序博客网 时间:2024/06/05 23:49
#include<cstdio>#include<cstring>#include<iostream>#include<iomanip>#include<queue>#include<cmath>#include<stack>#include<map>#include<vector>#include<set>#include<algorithm>using namespace std;typedef long long LL;const int int_max = 0x07777777;const int int_min = 0x80000000;const int maxn = 1000;struct HeapNode{    int u,d;    bool operator < (const HeapNode& a) const {        return d > a.d;    }};struct Edge {    int from, to, dist;};int n,m;         //点数和边数vector<Edge> edges;vector<int> g[maxn];bool done[maxn];int d[maxn],p[maxn];void addedge (int from, int to, int dist){    edges.push_back((Edge){from, to, dist});   //若是无向图,则一个边要调用两次这个函数    m = edges.size();    g[from].push_back(m-1);}void dij (int s){    for(int i = 0; i < maxn; i++) d[i] = int_max;    d[s] = 0;    priority_queue<HeapNode> q;    q.push((HeapNode){s,0});    while(!q.empty()){        HeapNode x = q.top();        q.pop();        int u = x.u;        if(done[u]) continue;        done[u] = true;        for(int i = 0; i < g[u].size(); i++){            Edge& e = edges[g[u][i]];            if(d[e.to] > d[e.from] + e.dist){                d[e.to] = d[e.from] + e.dist;                p[e.to] = g[u][i];                q.push((HeapNode){e.to,d[e.to]});            }        }    }}

用数组保存图,可以提高效率,参考如下。

#include<cstdio>#include<cstring>#include<iostream>#include<iomanip>#include<queue>#include<cmath>#include<stack>#include<map>#include<vector>#include<set>#include<algorithm>using namespace std;typedef long long LL;const int int_max = 0x07777777;const int int_min = 0x80000000;const int maxn = 31000;const int maxm = 160000;struct HeapNode{    int u,d;    HeapNode(int _u, int _d):u(_u),d(_d){}    bool operator < (const HeapNode& a) const {        return d > a.d;    }};struct Edge {    int e,v;}es[160000];int neg;int node[maxn];int nexte[maxm];int n,m; bool done[maxn];int d[maxn],p[maxn];void addedge (int s, int e, int v){    es[neg].e = e;    es[neg].v = v;    nexte[neg] = node[s];    node[s] = neg++;}void dij (int s){    for(int i = 0; i <= n; i++) d[i] = int_max;    memset(done, 0, sizeof(done));    d[s] = 0;    priority_queue<HeapNode> q;    q.push(HeapNode(s,0));    while(!q.empty()){        HeapNode x = q.top();        q.pop();        int u = x.u;        if(done[u]) continue;        done[u] = true;        int p = node[u];        while (p!=-1) {            if(d[es[p].e] > d[u]+es[p].v){                d[es[p].e] = d[u]+es[p].v;                q.push(HeapNode(es[p].e,d[es[p].e]));            }            p = nexte[p];        }    }}


0 0