跳到正文

个人记录

我,重振SPFA荣光!!

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

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟

版本

  1. v1当前

SPFA AC 优先队列优化

C++
#include <bits/stdc++.h>
using namespace std;
struct st{
	int to,w,nxt;
}edge[200005];
int head[100005];
int d[100005];
int cnt,s;
void gbc(int u,int v,int w){
	edge[++cnt].to=v;
	edge[cnt].w=w;
	edge[cnt].nxt=head[u];
	head[u]=cnt;
}
int n,m;
void spfa(){
	memset(d,0x3f,sizeof(d));
	priority_queue<pair<int , int > > q;
	q.push(make_pair(0,s));
	d[1]=0;
	while (1){
		int u=q.top().second;
		q.pop();
		for (int i=head[u];i;i=edge[i].nxt){
			if (d[u]+edge[i].w<d[edge[i].to]){
				d[edge[i].to]=d[u]+edge[i].w;
				q.push(make_pair(-d[edge[i].to],edge[i].to));
			}
		}
		if (q.empty()) return ;
		while(d[q.top().second]<-q.top().first){
			q.pop();
			if (q.empty()) return ;
		}
	}
}
int main (){
	cin>>n>>m>>s;
	for (int i=1;i<=m;i++){
		int a,b,c;
		cin>>a>>b>>c;
		gbc(a,b,c);
	}
	spfa();
	for (int i=1;i<=n;i++){
		cout<<d[i]<<' ';
	}
	return 0;
}
原文