DIJKSTRA(G, w, s) 1 INITIALIZE-SINGLE-SOURCE(G, s) 2 S <- Ø 3 Q <- V[G] 4 while Q ≠ Ø 5 do u <- EXTRACT-MIN(Q) 6 S <- S ∪ {u} 7 for each vertex v ∈ Adj[u] 8 do RELAX(u,v,w)
#include<bits/stdc++.h> #define ll long long #define int long long #define ios ios::sync_with_stdio(0),cin.tie(0) #define N 105 #define FOR(i,n) for(int i=0;i<n;i++) #define pii pair<int,int> usingnamespace std;
voidsolve(){ vector<pii> edge[N]; //存圖 int n,m,s,e,f;cin>>n>>m>>s>>e>>f; int dis[N];fill(dis,dis+N,1e16); bool visit[N]; //城市數n、方案數m、s起、e終、f箱數 memset(visit,0,sizeof(visit)); for(int i=0;i<m;i++){ int a,b,c,d,e;cin>>a>>b>>c>>d>>e; //一條由a連到b的邊,權重c,流量超過d,則改權重c int val = (f>d?c*d+e*(f-d):c*f); edge[a].push_back({b,val}); } //Dijkstra priority_queue<pii,vector<pii>,greater<pii>> pq; //(距離,點) pq.push({0,s}); dis[s] = 0; while(!pq.empty()){ int cur = pq.top().second; pq.pop(); if(visit[cur])continue; for(auto i:edge[cur]){ int next = i.first,weight = i.second; if(dis[cur]+weight<dis[next]){ dis[next] = dis[cur]+weight; pq.push({dis[next],next}); } } visit[cur] = 1; } cout<<dis[e]<<endl; }
signedmain(){ ios; int t;cin>>t; while(t--){ solve(); } }
BELLMAN-FORD(G,w,s) 1 INITIALIZE-SINGLE-SOURCE(G,s) 2 for i <- 1 to |V[G]|-1 3 do for each edge (u,v)∈ E[G] 4 do RELAX(u,v,w) 5 for each edge (u,v)∈ E[G] 6 do if d[v] > d[u]+w(u,v) 7 then return FALSE 8 return TRUE
Shortest-Path-Faster-Algorithm(G, s) 1 for each vertex v ≠ s in V(G) 2 d(v) := ∞ 3 d(s) := 0 4 offer s into Q 5 while Q is not empty 6 u := poll Q 7 for each edge (u, v) in E(G) 8 if d(u) + w(u, v) < d(v) then 9 d(v) := d(u) + w(u, v) 10 if v is not in Q then 11 offer v into Q
#include<bits/stdc++.h> #define ll long long #define int long long #define ios ios::sync_with_stdio(0),cin.tie(0) #define N 105 #define FOR(i,n) for(int i=0;i<n;i++) #define pii pair<int,int> usingnamespace std;
voidsolve(){ vector<pii> edge[N]; //存圖 int n,m,s,e,f;cin>>n>>m>>s>>e>>f; int dis[N];fill(dis,dis+N,1e16); bool visit[N]; //城市數n、方案數m、s起、e終、f箱數 memset(visit,0,sizeof(visit)); for(int i=0;i<m;i++){ int a,b,c,d,e;cin>>a>>b>>c>>d>>e; //一條由a連到b的邊,權重c,流量超過d,則改權重c int val = (f>d?c*d+e*(f-d):c*f); edge[a].push_back({b,val}); } //SPFA queue<int> que; que.push(s); dis[s] = 0; visit[s] = 1; while(!que.empty()){ int cur = que.front(); que.pop(); visit[cur] = 0; //pop出來將狀態改成不在queue中 for(auto i:edge[cur]){ int next = i.first,weight = i.second; if(dis[next] > dis[cur]+weight){ dis[next] = dis[cur]+weight; if(!visit[next])que.push(next); } } } cout<<dis[e]<<endl; }
signedmain(){ ios; int t;cin>>t; while(t--){ solve(); } }