题解 | #最短路#
最短路
https://ac.nowcoder.com/acm/problem/14369
SPFA算法裸题
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int N =3e5+10;
int h[N],e[N],ne[N],idx,w[N];//邻接表存储
int n,m;//点 边
bool st[N];int dist[N];//状态 距离 数组
void add(int a,int b,int c)//点 点 权重
{
e[idx]=b;
ne[idx]=h[a];w[idx]=c;
h[a]=idx++;
}
void spfa()
{
memset(dist,0x3f,sizeof dist);//初始化距离数组
dist[1]=0;//起点距离为0
st[1]=false;//出队
queue<int>q;
q.push(1);
while(q.size())
{
int t=q.front();//出队
q.pop();
st[t]=false;//代表之后该节点如果发生更新可再次入队
for(int i=h[t];i != -1;i = ne[i])//更新到邻接点的距离
{
int j=e[i];
if(dist[j] > dist[t]+w[i])
{
dist[j]=dist[t]+w[i];
if(!st[j])//当前已经加入队列的结点,无需再次加入队列,即便发生了更新也只用更新数值即可,重复添加降低效率
{
st[j]=true;
q.push(j);
}
}
}
}
}
int main()
{
memset(h,-1,sizeof h);//-1 空指针数组
cin>>n>>m;
while(m--)
{
int a,b,c;cin>>a>>b>>c;
add(a,b,c);
}
spfa();
for(int i=2;i<=n;i++)
{
printf("%d\n",dist[i]);
}
return 0;
}