练习题 No.22 判断是否有负圈(Bellman-Ford算法)

来源:互联网 发布:上海市行知中学校徽 编辑:程序博客网 时间:2024/06/08 16:48

要求

给出一个有向图,让你求这个圈里是否有负权环

限制条件

输入格式

第一行输入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 10000000class 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;  }
0 0