bellman-ford最短路徑算法
bellman-ford 算法,是求單源點最短路徑的算法。
我們設從起點到其他點i的最短路爲d[i],
顯然滿足下列等式
含義是到一點的最短路肯定是,到與他相鄰的點的最短路加上邊的權值,最小的那條。
經過多次迭代上式就可以得到最短路徑。
如果圖中不存在負圈,那麼在最短路徑中一個頂點不可能經過2次。也就是說最多|V|-1條邊。最多迭代|V|-1次,每迭代一次似乎在多加1條邊的路徑一起比較。
該算法也可以判斷有無負圈,如果迭代超過|V|-1次,有負圈。
圖表示方法
之前提到過鄰接矩陣
現在介紹另一種邊集表示法
用邊集合來表示圖
struct edge{
int from;
int to;
int cost;
}
struct edge es[MAX_E];
顯然這種表示法需要遍歷所有邊纔可能知道點與點之間有無聯繫。
這種表示法可以表示點與點之間的多重邊。
這種方法非常適用於BF算法,因爲BF算法迭代式中是針對邊的。
例題POJ 3259(蟲洞問題,判斷負圈是否存在)
Wormholes
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 80546 Accepted: 29846
Description
While exploring his many farms, Farmer John has discovered a number of amazing wormholes. A wormhole is very peculiar because it is a one-way path that delivers you to its destination at a time that is BEFORE you entered the wormhole! Each of FJ’s farms comprises N (1 ≤ N ≤ 500) fields conveniently numbered 1…N, M (1 ≤ M ≤ 2500) paths, and W (1 ≤ W ≤ 200) wormholes.
As FJ is an avid time-traveling fan, he wants to do the following: start at some field, travel through some paths and wormholes, and return to the starting field a time before his initial departure. Perhaps he will be able to meet himself 😃 .
To help FJ find out whether this is possible or not, he will supply you with complete maps to F (1 ≤ F ≤ 5) of his farms. No paths will take longer than 10,000 seconds to travel and no wormhole can bring FJ back in time by more than 10,000 seconds.
Input
Line 1: A single integer, F. F farm descriptions follow.
Line 1 of each farm: Three space-separated integers respectively: N, M, and W
Lines 2…M+1 of each farm: Three space-separated numbers (S, E, T) that describe, respectively: a bidirectional path between S and E that requires T seconds to traverse. Two fields might be connected by more than one path.
Lines M+2…M+W+1 of each farm: Three space-separated numbers (S, E, T) that describe, respectively: A one way path from S to E that also moves the traveler back T seconds.
Output
Lines 1…F: For each farm, output “YES” if FJ can achieve his goal, otherwise output “NO” (do not include the quotes).
代碼
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
//bf
//cost
//圖的邊表示
struct edge{
int from;
int to;
int cost;
};
const int MAX_E=2801;
edge e[MAX_E*2];
bool negtive_circle(){
int N,M,W;
cin >>N>>M>>W;
int a,b,c;
int i=0;
for(i=0;i<M;i++){
cin>>a>>b>>c;
e[2*i].from=a;
e[2*i].to=b;
e[2*i].cost=c;
e[2*i+1].from=b;
e[2*i+1].to=a;
e[2*i+1].cost=c;
}
int j=i*2;
for(int k=0;k<W;j++,k++){
cin>>a>>b>>c;
e[j].from=a;
e[j].to=b;
e[j].cost=-c;
}
int s=e[0].from;
int E=j;
vector<int> d(N+1,INT_MAX);
d[s]=0;
for(int v=0;v<N;v++){
for(int i=0;i<E;i++){
edge ee=e[i];
//這一句很關鍵
if(d[ee.from]!=INT_MAX&&d[ee.to]>d[ee.from]+ee.cost){
d[ee.to]=d[ee.from]+ee.cost;
if(v==N-1) return true;
}
}
}
return false;
}
int main(){
int f;
cin>>f;
while(f--){
bool res=negtive_circle();
if(res)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}