首页 > 代码库 > HDU 1847(SPFA)
HDU 1847(SPFA)
高仿代码:
#include <iostream>
#include <string.h>
#include <queue>
#include <vector>
#include <utility>
#include <cstdio>
using namespace std;
#define N 205
#define M 2005
const int inf = 0x3f3f3f3f;
int v[M],w[M],next[M],first[N],d[N],e;
bool inq[N];
void addedge(int a,int b,int x){
v[e]=b;
w[e]=x;
next[e]=first[a];
first[a]=e++;
}
void SPFA(int st){
queue<int> q;
d[st]=0;
q.push(st);
inq[st]=1;
while(!q.empty()){
int u = q.front();
q.pop();
inq[u] = 0;
for(int i=first[u];i!=-1;i=next[i]){
if(d[v[i]]>d[u]+w[i]){
d[v[i]]=d[u]+w[i];
if(!inq[v[i]]){
q.push(v[i]);
inq[v[i]]=1;
}
}
}
}
}
int main(){
int n,m,a,b,x;
//freopen("test.txt","r",stdin);
while(cin>>n>>m){
e=0;
for(int i=0;i<n;i++){
first[i]=-1;
inq[i]=false;
d[i]=inf;
}
for(int i=0;i<m;i++){
cin>>a>>b>>x;
addedge(a,b,x);
addedge(b,a,x);
}
cin>>a>>b;
SPFA(a);
if(d[b]==inf)cout<<"-1"<<endl;
else cout<<d[b]<<endl;
}
return 0;
}