<strong><span style="font-size:18px;"> 转自:http://blog.csdn.net/cnyali/article/details/47664329</span></strong> #include<stdio.h> #include<string.h> #include<stdlib.h> const int maxn=100,INF=1000000000; int a[maxn][maxn],p[maxn],d[maxn],q[maxn*maxn]; int main(){ freopen("spfa.in","r",stdin); freopen("spfa.out","w",stdout); int i,j,k,m,n; int x,y,z; scanf("%d%d",&n,&m); for(i=1;i<=m;i++){ scanf("%d%d%d",&x,&y,&z); a[x][y]=z; } for(i=1;i<=n;i++)d[i]=INF; d[1]=0; q[1]=1; p[1]=1; int f=0,l=1; while(f<l){ f++;k=q[f]; for(i=1;i<=n;i++) if(a[k][i] && d[i]>d[k]+a[k][i]){ d[i]=d[k]+a[k][i]; if(!p[i]){ q[++l]=i; p[i]=1; } } p[k]=0; } for(i=1;i<=n;i++)printf("%d ",d[i]); return 0; }