题解
【入门】有负权边的最短路
1 条题解
-
0
#include<bits/stdc++.h> using namespace std; const int N=20005,M=200005; int h[N],e[M],w[M],ne[M],idx; int d[N],v[N],cnt[N]; int n,m; void add(int a,int b,int c){ e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++; } void spfa(){ queue<int>q; for(int i=1;i<=n;i++)d[i]=1e9; d[1]=0; q.push(1); v[1]=1; while(!q.empty()){ int t=q.front(); q.pop(); v[t]=0; for(int i=h[t];~i;i=ne[i]){ int j=e[i]; if(d[j]>d[t]+w[i]){ d[j]=d[t]+w[i]; if(!v[j]){ q.push(j); v[j]=1; } } } } } int main(){ memset(h,-1,sizeof h); scanf("%d%d",&n,&m); for(int i=1;i<=m;i++){ int u,v,l; scanf("%d%d%d",&u,&v,&l); add(u,v,l); } spfa(); for(int i=2;i<=n;i++)printf("%d\n",d[i]); return 0; }
- 1