單源最短路徑模板題,沒什麼好說的。ios
然而本題卡普通SPFA.....git
昨天某位同窗給我說了堆優化SPFA.... 因而就拿來寫這道題,A了優化
堆優化思想就是把dis小的放在前邊,也許和SLF優化差很少? 然而感受上比SLF快不少spa
#include<algorithm> #include<iostream> #include<cstring> #include<cstdio> #include<queue> using namespace std; bool inque[400100]; int to[400100],nex[400100],val[400100],head[400100],dis[400100]; struct cmp { bool operator () (int &x,int &y) { return dis[x]>dis[y]; } }; priority_queue <int,vector<int>,cmp> q; char buf[1000100]; inline char nc() { static char buf[1000000],*p1=buf,*p2=buf; return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++; } inline int read() { int sum=0; char ch=nc(); while(!isdigit(ch)) ch=nc(); while(isdigit(ch)) { sum=(sum<<3)+(sum<<1)+(ch^48); ch=nc(); } return sum; } inline void putd(int x) { int p=0; if(x<0) { putchar('-'); x=-x; } do { buf[p++]=x%10; x/=10; }while(x); for(register int i=p-1;i>=0;i--) putchar(buf[i]+'0'); putchar(' '); } void spfa(int s) { int now; inque[s]=true; q.push(s); dis[s]=0; while(!q.empty()) { now=q.top(); q.pop(); inque[now]=false; for(register int i=head[now]; i; i=nex[i]) { if(dis[to[i]]>dis[now]+val[i]) { dis[to[i]]=dis[now]+val[i]; if(!inque[to[i]]) { inque[to[i]]=true; q.push(to[i]); } } } } return ; } int main() { int n,m,s,f,t,v; n=read(); m=read(); s=read(); memset(dis,0x7f,sizeof(dis)); for(register int i=1; i<=m; i++) { f=read(); t=read(); v=read(); to[i]=t; val[i]=v; nex[i]=head[f]; head[f]=i; } spfa(s); for(register int i=1; i<=n; i++) putd(dis[i]); return 0; }