zoukankan      html  css  js  c++  java
  • 最短路dijkstra+spfa

    #include<cstdio> 
    #include<cstring>
    #include<cmath>
    #include<iostream>
    #include<algorithm>
    #include<queue>
    #include<set>
    #define maxint (2147483647)
    #define l(a) ((a)<<1)
    #define r(a) ((a)<<1|1)
    #define b(a) (2<<(a))
    #define rep(i,a,b) for(int i=a;i<=(b);i++)
    #define Rep(e,x) for(edge*e=fir[x];e;e=e->next) 
    #define clr(a) memset(a,0,sizeof(a))
    typedef long long ll;
    using namespace std;
    int readint(){
        int t=0,f=1;char c=getchar();
        while(!isdigit(c)){
            if(c=='-') f=-1;
            c=getchar();
        }
        while(isdigit(c)){
            t=(t<<3)+(t<<1)+c-'0';
            c=getchar();
        }
        return t*f;
    }
    const int maxn=10009,maxm=500009;
    int n,m,S,d[maxn];
    bool p[maxn];
    struct node{
        int x,d;
        inline bool operator<(const node N)const{
            return d>N.d;
        }
        node(int a,int b){
            x=a;d=b;
        }
    };
    struct edge{
        int v,w;
        edge*next;
    }e[maxm],*fir[maxn],*pt=e;
    void addedge(int u,int v,int w){
        pt->v=v;pt->w=w;
        pt->next=fir[u];
        fir[u]=pt++;
    }
    void dijkstra(){
        rep(i,1,n) d[i]=maxint;d[S]=0;
        priority_queue<node>Q;Q.push(node(S,0));
        while(!Q.empty()){
            node x=Q.top();Q.pop();
            if(x.d==d[x.x]) Rep(e,x.x){
                if(d[e->v]>d[x.x]+e->w){
                    d[e->v]=d[x.x]+e->w;
                    Q.push(node(e->v,d[e->v]));
                }
            }
        }
    }
    void spfa(){
        rep(i,1,n) d[i]=maxint;d[S]=0;
        queue<int>Q;Q.push(S);p[S]=1;
        while(!Q.empty()){
            int x=Q.front();Q.pop();p[x]=0;
            Rep(e,x){
                if(d[e->v]>d[x]+e->w){
                    d[e->v]=d[x]+e->w;
                    if(!p[e->v]){
                        Q.push(e->v);p[e->v]=1;
                    }
                }
            }
        }
    }
    int main(){
        //freopen("#input.txt","r",stdin);
        //freopen("#output.txt","w",stdout);
        n=readint();m=readint();S=readint();
        rep(i,1,m){
            int u=readint(),v=readint(),w=readint();
            addedge(u,v,w);    
        }
        spfa();
        rep(i,1,n){
            printf("%d",d[i]);
            if(i!=n) putchar(' ');
        }
        //fclose(stdin);
        //fclose(stdout);
        return 0;
    }
    最短路
  • 相关阅读:
    美团面试(c++方向)
    浪潮面试-软开
    ofo C++面试
    B树、B+树等
    爱奇艺2017秋招笔试(C++智能设备方向)
    腾讯内推一面C++
    i++ 相比 ++i 哪个更高效?为什么?
    进程间的通讯(IPC)方式
    一台服务器能够支持多少TCP并发连接呢?
    可重入和不可重入
  • 原文地址:https://www.cnblogs.com/chensiang/p/7665981.html
Copyright © 2011-2022 走看看