problem
- 给出一个有向图
- 求从某一点出发到所有点的最短路
solution
SPFA
codes
#include<iostream>
#include<queue>
#include<cstring>
#define maxn 10010
#define maxm 500010
using namespace std;
//Grape
int n, m, s;
struct Edge{int v, w, next;}e[maxm<<1];
int tot, head[maxn];
void AddEdge(int u, int v, int w){
tot++; e[tot].v=v; e[tot].w=w; e[tot].next=head[u]; head[u]=tot;
}
//SPFA
int dist[maxn], book[maxn];
queue<int>q;
void spfa(){
for(int i = 1; i <= n; i++)dist[i]=2147483647;
dist[s]=0; book[s]=1; q.push(s);
while(q.size()){
int u = q.front(); q.pop(); book[u]=0;
for(int i = head[u]; i > 0; i = e[i].next){
int v = e[i].v, w = e[i].w;
if(dist[v]>dist[u]+w){
dist[v] = dist[u]+w;
if(!book[v]){
book[v] = 1; q.push(v);
}
}
}
}
}
int main(){
cin>>n>>m>>s;
for(int i = 1; i <= m; i++){
int x, y, z; cin>>x>>y>>z; AddEdge(x,y,z);
}
spfa();
for(int i = 1; i <= n; i++)
cout<<dist[i]<<' ';
return 0;
}
标签:dist,Luogu3371,int,单源,next,SPFA,include,define
From: https://blog.51cto.com/gwj1314/6043782