【图论】快速最短路SPFA算法

封装后的模板:
以hdoj1874为例
在这里插入图片描述

#include<bits/stdc++.h>
#define ll long long
#define endl '\n'
using namespace std;
const int INF=0x3f3f3f3f;
const int maxn=5050;
vector<pair<ll,ll> > edge[maxn];
ll n,m,s,t;
ll d[maxn],inq[maxn];queue<ll> q; 
void init(){
	for(ll i=0;i<maxn;i++) edge[i].clear();
	for(ll i=0;i<maxn;i++) inq[i]=0;
	for(ll i=0;i<maxn;i++) d[i]=INF;
}
void SPFA(ll s){
	q.push(s);d[s]=0,inq[s]=1;
	while(!q.empty()){
		ll now=q.front();
		q.pop();inq[now]=0;
		for(ll i=0;i<edge[now].size();i++){
			ll v=edge[now][i].first;
			if(d[v]>d[now]+edge[now][i].second){
				d[v]=d[now]+edge[now][i].second;
				if(inq[v]==1) continue;
				inq[v]=1,q.push(v);
			}
		}
	}
}
int main(){
	while(cin>>n>>m){
		init();
		for(ll i=1;i<=m;i++){
			ll u,v,w;cin>>u>>v>>w;
			edge[u].push_back(make_pair(v,w));
			edge[v].push_back(make_pair(u,w));
		}
		cin>>s>>t;
		SPFA(s);
		if(d[t]<INF) cout<<d[t]<<endl;
		else cout<<"-1"<<endl;
	}
}

/*
3 3
0 1 1
0 2 3
1 2 1
0 2
3 1
0 1 1
1 2
*/
//output 2 -1

这里运用了BFS的做法
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值