模板 最短路径

堆优化Dijkstra

#include <cstdio>
#include <algorithm>
#include <string>
#include <queue>
#define MAXN 500005

struct Node {
    int u,dis;
    inline bool operator < (const Node& node) const {
        return dis > node.dis;
    }
};

std::priority_queue < Node > q;

struct edge {
    int u,v,w,next;
} G[MAXN<<1];

int head[MAXN],vis[MAXN],dis[MAXN];
int N,M,S,tot = 0;

inline void add(int u,int v,int w) {
    G[++tot].v = v; G[tot].w = w; G[tot].next = head[u]; head[u] = tot;
}

int main() {

    scanf("%d%d%d",&N,&M,&S);
    for(int i=1;i<=M;++i) {
        int u,v,w; scanf("%d%d%d",&u,&v,&w);
        add(u,v,w); 
    }

    for(int i=1;i<=N;++i) dis[i] = 2147483647;
    dis[S] = 0; q.push( (Node){S,0} );

    while(!q.empty()) {
        
        int u = q.top().u; q.pop();
        if(vis[u]) continue; vis[u] = 1;
        for(int i=head[u];i;i=G[i].next) {
            int v = G[i].v; int w = G[i].w;
            if(dis[v]>dis[u]+w) q.push( (Node){v,dis[v]=dis[u]+w} );
        }
    }

    for(int i=1;i<=N;++i) printf("%d ",dis[i]);
    return 0;
}

SPFA

#include <cstdio>
#include <algorithm>
#include <string>

#define MAXN 524287

struct queue {
    long long l,r; int q[MAXN];
    queue() : l(1),r(0) {}
    inline void push(int x) {
        q[(++r)&MAXN] = x;
    }
    inline void pop() { l++; }
    inline int front() {
        return q[l&MAXN];
    }
    inline bool empty() { return l>r; }
} q;

struct edge {
    int v,w,next;
} G[MAXN<<1];

int head[MAXN],vis[MAXN],dis[MAXN];
int N,M,S,tot = 0;

inline void add(int u,int v,int w) {
    G[++tot].v = v; G[tot].w = w; G[tot].next = head[u]; head[u] = tot;
}

int main() {

    scanf("%d%d%d",&N,&M,&S);
    for(int i=1;i<=M;++i) {
        int u,v,w; scanf("%d%d%d",&u,&v,&w);
        add(u,v,w);
    }

    for(int i=1;i<=N;++i) {
        vis[i] = 0; dis[i] = 2147483647;
    }

    dis[S] = 0; vis[S] = 1; q.push(S);
    while(!q.empty()) {
        int u = q.front(); q.pop();
        for(int i=head[u];i;i=G[i].next) {
            int v = G[i].v; int w = G[i].w;
            if(dis[v]>dis[u]+w) {
                dis[v] = dis[u] + w;
                if(!vis[v]) {
                    q.push(v);
                    vis[v] = 1;
                }
            }
        }
        vis[u] = 0;
    }

    for(int i=1;i<=N;++i) printf("%d ",dis[i]);
    return 0;
}
posted @ 2021-09-03 00:28  Neworld1111  阅读(28)  评论(0编辑  收藏  举报