spfa模板
【代码】
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
#include<set>
using namespace std;
#define f(i,n) for(int i=1;i<=(n);i++)
#define ll long long
#define INF 1<<30
#define N 100010
#define M 200010
int n,m;
int read()
{
int x=0,f=1;char c=getchar();
while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
while( isdigit(c)){x=x*10+c-'0';c=getchar();}
return x*f;
}
struct xj
{
int y;
int next;
int v;
}map[2*M];
int cnt;
int head[N];
void add_edge(int u,int v,int z)
{
map[++cnt].y=v;
map[cnt].v=z;
map[cnt].next=head[u];
head[u]=cnt;
}
queue<int> q;
int vis[N],dis[N];
void spfa()
{
memset(vis,0,sizeof(vis));
f(i,n)dis[i]=INF;
while(q.size())q.pop();
dis[1]=0;
vis[1]=1;
q.push(1);
while(q.size())
{
int x=q.front();
q.pop();
for(int i=head[x];i;i=map[i].next)
{
if(dis[map[i].y]>dis[x]+map[i].v)
{
dis[map[i].y]=dis[x]+map[i].v;
if(!vis[map[i].y])
{
q.push(map[i].y);
vis[map[i].y]=1;
}
}
}
vis[x]=0;
}
}
int main()
{
n=read();
m=read();
int u,v,z;
f(i,m)
{
u=read();
v=read();
z=read();
add_edge(u,v,z);
add_edge(v,u,z);
}
spfa();
f(i,n)printf("%d ",dis[i]);
}