最短路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;
}
最短路

 

posted @ 2017-10-14 10:50  ChenThree  阅读(133)  评论(0编辑  收藏  举报