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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| #include <bits/stdc++.h> using namespace std; const int N = 510, M = 100010; int n, m, k; int dist[N], backcup[N]; struct Edge { int a, b, w; }edges[M]; int bellman_ford() { memset(dist,0x3f,sizeof(dist)); dist[1]=0; for(int i=0;i<k;i++) { memcpy(backcup,dist,sizeof(dist)); for(int j=0;j<m;j++) { int a=edges[j].a, b=edges[j].b, w=edges[j].w; dist[b]=min(dist[b], backcup[a]+w); } } if(dist[n]>0x3f3f3f3f/2) return -1; return dist[n]; } int main() { cin>>n>>m>>k; for(int i=0;i<m;i++) { int a,b,w; cin>>a>>b>>w; edges[i]={a,b,w}; } int t=bellman_ford(); if(t==-1) cout<<"impossible"<<endl; else cout<<t<<endl; return 0; }
-----------------------------------------------分割线---------------------------------------------------
#include <bits/stdc++.h> using namespace std; const int N = 510, M = 100010; int n, m, cnt; int dist[N], backcup[N], dot[N]; struct Edge { int a, b, w; }edges[M]; long long bellman_ford(int start,int end) { memset(dist,0x3f3f3f3f,sizeof(dist)); dist[start]=0; for(int i=0;i<1200;i++) { memcpy(backcup,dist,sizeof(dist)); for(int j=0;j<cnt;j++) { int a=edges[j].a, b=edges[j].b, w=edges[j].w; dist[b]=min(dist[b], backcup[a]+w); } }
if(dist[end]>0x3f3f3f3f/2) return 9999; return dist[end]; } int main() { while(1) { cin>>n>>m; cnt=0; if(n==0&&m==0) break; for(int i=1;i<=n;i++) cin>>dot[i]; for(int i=0;i<m;i++) { int a,b,c; cin>>a>>b>>c; int tmp=dot[c]-dot[b]; if(a==1){ edges[cnt++]={b,c,tmp}; } else{ edges[cnt++]={b,c,tmp}, edges[cnt++]={c,b,tmp*-1}; } } int start, end; cin>>start>>end; int t=bellman_ford(start,end); if(t==9999) cout<<"INF"<<endl; else cout<<t<<endl; } return 0; }
|