【模板】spfa
阿新 • • 發佈:2018-11-03
程式碼如下
#include <bits/stdc++.h> using namespace std; const int maxv=1e4+10; const int maxe=5e5+10; const int inf=0x3f3f3f3f; inline int read(){ int x=0,f=1;char ch; do{ch=getchar();if(ch=='-')f=-1;}while(!isdigit(ch)); do{x=x*10+ch-'0';ch=getchar();}while(isdigit(ch)); return f*x; } struct node{ int nxt,to,w; }e[maxe]; int tot=1,head[maxv]; inline void add_edge(int from,int to,int w){ e[++tot]=node{head[from],to,w},head[from]=tot; } int n,m,st,dis[maxv]; void read_and_parse(){ n=read(),m=read(),st=read(); for(int i=1,from,to,w;i<=m;i++){ from=read(),to=read(),w=read(); add_edge(from,to,w); } } bool in[maxv]; void spfa(){ memset(dis,0x3f,sizeof(dis)); queue<int> q; q.push(st),in[st]=1,dis[st]=0; while(q.size()){ int u=q.front();q.pop();in[u]=0; for(int i=head[u];i;i=e[i].nxt){ int v=e[i].to,w=e[i].w; if(dis[v]>dis[u]+w){ dis[v]=dis[u]+w; if(!in[v])q.push(v); } } } for(int i=1;i<=n;i++){ if(dis[i]==inf)printf("2147483647 "); else printf("%d ",dis[i]); } puts(""); } int main(){ read_and_parse(); spfa(); return 0; }