跳到正文

个人记录

最短路(SPFA)

Zzzsh约 2 分钟
原文
文章信息与版本

文章信息

发布
2019年8月7日
收录
2026年5月6日
更新
2026年11月16日
篇幅
约 2 分钟

版本

  1. v2当前
  2. v1
C++
#include<bits/stdc++.h>
const long long inf=2147483647;
const int maxn=10005;
const int maxm=500005;
using namespace std;
int n,m,s,tot=0;
int dis[maxn],vis[maxn],head[maxm];
struct Edge
{
  	int next,to,d;
}edge[maxm];
void add(int x,int y,int z) //邻接表建图
{
	edge[++tot].to=y;
	edge[tot].d=z;
	edge[tot].next=head[x];
	head[x]=tot;
}
void spfa()
{
	queue<int> q;
	for(int i=1; i<=n; i++) dis[i]=inf;
	q.push(s);
	dis[s]=0;
	vis[s]=1;
	while(!q.empty())
	{
		int u=q.front();
		q.pop();
		vis[u]=0;
		for(int i=head[u]; i; i=edge[i].next)
		{
	  		int v=edge[i].to;
	  		if(dis[v]>dis[u]+edge[i].d)
	  		{
	    		dis[v]=dis[u]+edge[i].d;
	    		if(vis[v]==0)
	    		{
	      			vis[v]=1;
	      			q.push(v);
	    		}
	  		}
		}
	}
}
int main()
{
	cin>>n>>m>>s;
	for(int i=1; i<=m; i++)
	{
		int f,g,w;
		cin>>f>>g>>w;
		add(f,g,w);
	}
	spfa();
	for(int i=1; i<=n; i++) cout<<dis[i]<<" ";

  	return 0;
}
原文