Bellman-Ford算法

来源:互联网 发布:淘宝怎么买彩票 编辑:程序博客网 时间:2024/06/02 07:47
<span style="font-size:14px;">//Bellman-Ford_001.cpp -- 单源最短路#include <iostream>#include <algorithm>#include <cstring>#include <cstdlib>#include <cstdio>#include <cmath>#include <queue>#include <vector>#include <map>typedef long long ll;using namespace std;const int INF = 0x3f3f3f3f;const int maxE = 1000 + 10;const int maxV = 100 + 10;struct edge{int from, to, cost;};edge es[maxE];int d[maxV];int V, E;void Bellman_Ford(int s){fill(d, d+V, INF);d[s] = 0;for( int i=0; i<V-1; i++ ){bool update = false;for( int j=0; j<E; i++ ){edge e = es[j];if( d[e.from]!=INF && d[e.to]>d[e.from]+e.cost ){d[e.to] = d[e.from] + e.cost;update = true;}}if( !update )break;}bool flag = false;for( int i=0; i<E; i++ ){edge e = es[i];if( d[e.from]!=INF && d[e.to]>d[e.from]+e.cost ){flag = true;break;}}if( flag )cout<<"存在负圈。"<<endl;} int main(){while( cin>>V>>E && V ){int a, b, c;for( int i=0; i<E; i++ ){cin>>a>>b>>c;es[i] = (edge){a, b, c};}Bellman_Ford(0);}return 0;}</span>

0 0
原创粉丝点击