封装后的模板:
以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的做法