求单源最短路模板 spfa

模板:

#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef pair<int, int>PII;
const int N=2e5+10;
const int MOD = 998244353;
const int INF=0X3F3F3F3F;
const int dx[]={-1,1,0,0,-1,-1,+1,+1};
const int dy[]={0,0,-1,1,-1,+1,-1,+1};
const int M = 1e6 + 10;

//好累啊
//spfa算法求最短路时间复杂度最坏n * m

int n, m, s, t;
vector<PII>ed[N];
int dis[N];
queue<int>q;
bool st[N];

void spfa()
{
	memset(dis, 0x3f, sizeof dis);
	for(int i = 1; i <= m; i ++)
	{
		int u, v, w;
		cin >> u >> v >> w;
		ed[u].push_back({v, w});
		ed[v].push_back({u, w});//因为是无向图
	}
	dis[s] = 0;
	st[s] = true;
	q.push(s);
	while(!q.empty()){
		int x = q.front();
		q.pop();
		st[x] = false;
		for(auto it : ed[x])
		{
			if(dis[it.first] <= dis[x] + it.second) continue;
			dis[it.first] = dis[x] + it.second;
			if(!st[it.first])
			{
				st[it.first] = true;
				q.push(it.first);
			}
 		}
	}
}
int main()
{
	cin >> n >> m >> s >> t;//起点跟终点
	spfa();
	cout << dis[t] << endl;
	return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值