用到了 Bellman-Ford Shortist Path Algorithm
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| #include<iostream> using namespace std; #define INF 1e9
struct edge{ int from,to,cost; };
int d[505],c[505],n,m; edge a[10050];
void shortistPath(){ while(1){ bool update=false; for(int i=0;i<2*m;i++){ if(d[a[i].from]!=INF && d[a[i].to]>d[a[i].from]+a[i].cost+c[a[i].to]){ d[a[i].to]=d[a[i].from]+a[i].cost+c[a[i].to]; update=true; } } if(!update) break; } }
int main(){ ios::sync_with_stdio(false);cin.tie(0);
cin>>n; for(int i=1;i<=n;i++){ cin>>c[i]; d[i]=INF; } cin>>m; for(int i=0;i<m;i++){ cin>>a[i].from>>a[i].to>>a[i].cost; a[m+i].from=a[i].to; a[m+i].to=a[i].from; a[m+i].cost=a[i].cost; } d[1]=0; shortistPath(); if(d[n]!=INF){ cout<<d[n]; }else{ cout<<"-1"; } return 0; }
|