代码如下:
#include<bits/stdc++.h> using namespace std; const int N=1e6+7; int n,m,top,x[N],y[N],z[N],dis[N],head[N]; bool vis[N]; struct node{ int too,next,zh; }edge[N]; void add(int a,int b,int c) { edge[++top].too=b;edge[top].zh=c; edge[top].next=head[a];head[a]=top; } void spfa() { queue<int>q; q.push(0); while(!q.empty()) { int u=q.front();q.pop(); vis[u]=false; for(int i=head[u];i>=0;i=edge[i].next) { int v=edge[i].too; if(dis[v]>dis[u]+edge[i].zh) { dis[v]=dis[u]+edge[i].zh; if(!vis[v]) { q.push(v); vis[v]=true; } } } } } int main() { memset(head,-1,sizeof(head)); scanf("%d%d",&n,&m); for(int i=1;i<=n;i++)dis[i]=1e9; for(int i=1;i<=m;i++) { scanf("%d%d%d",&x[i],&y[i],&z[i]); add(x[i],y[i],z[i]); } for(int i=1;i<=n;i++)add(0,i,0); spfa(); for(int i=1;i<=m;i++) printf("%d %d %d\n",x[i],y[i],dis[x[i]]+z[i]-dis[y[i]]); return 0; }