首页 > 代码库 > HDU 1847(Bellman-Ford)
HDU 1847(Bellman-Ford)
高仿代码:
#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],u[M],d[N],w[M],e;
void addedge(int a,int b,int x){
v[e]=b;
u[e]=a;
w[e++]=x;
}
void bellman_ford(int n){
for(int i=0;i<n;i++){
for(int j=0;j<e;j++){
if(d[v[j]]>d[u[j]]+w[j])
d[v[j]]=d[u[j]]+w[j];
}
}
}
int main(){
int n,m,a,b,x;
//freopen("test.txt","r",stdin);
while(cin>>n>>m){
e=0;
memset(d,0x3f,sizeof(d));
for(int i=0;i<m;i++){
cin>>a>>b>>x;
addedge(a,b,x);
addedge(b,a,x);
}
cin>>a>>b;
d[a]=0;
bellman_ford(n);
if(d[b]==inf)cout<<"-1"<<endl;
else cout<<d[b]<<endl;
}
return 0;
}