練習題 No.22 判斷是否有負圈(Bellman-Ford演算法)
阿新 • • 發佈:2019-02-12
要求
給出一個有向圖,讓你求這個圈裡是否有負權環
限制條件
無
輸入格式
第一行輸入V,E分別代表頂點數和邊數
接下來E行,每行輸入from to cost 代表從from到to的距離為cost
最後一行輸入start end
輸出格式
有輸出1,否則輸出0
測試輸入
5 5
0 1 1
1 2 -5
2 0 1
2 4 4
3 0 1
3 4
測試輸出
1
解題思路
從start出發。不斷維護每個點的最短距離,如果有負權環,則會進行無數次的維護,越來越小,所以如果迴圈次數大於了V - 1則有負權環。
程式碼
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 10000000
class Node {
public:
int from;
int to;
int cost;
};
Node es[MAX];
int dist[MAX];
int V, E;
bool shortestPath(int s) {
fill(dist, dist + V, 0x7f7f);
dist[s] = 0;
int n = 0;
while (true) {
bool update = false;
for (int i = 0; i < E; i++) {
Node e = es[i];
if (dist[e.from] != 0x7f7f && dist[e.to] > dist[e.from] + e.cost) {
dist[e.to] = dist[e.from] + e.cost;
update = true;
}
}
if (!update) {
break ;
}
if (n == V - 1) {
return true;
}
n++;
}
return false;
}
int main() {
cin >> V >> E;
for (int i = 0; i < E; i++) {
cin >> es[i].from >> es[i].to >> es[i].cost;
}
int start, end;
cin >> start >> end;
cout << shortestPath(start) << endl;
return 0;
} cin >> start >> end;
shortestPath(start);
cout << dist[end] << endl;
return 0;
}