bellman-ford算法的变形。
传统bellman是求最短路径,这里变形为求最长路径。
松弛结束后,遍历各边,如还有可松弛的边,则说明存在正向环,可无限增长,如此则解为YES。
#include <iostream>
using namespace std;
struct Edge{
int A;
int B;
double r;
double c;
};
int N,M;
int S;
double v;
Edge edges[200];
int num_edges = 0;
double d[101];
bool bellman(){
d[S] = v;
for(int i=1;i<N;++i){
for(int j=0;j<num_edges;++j){
double t = (d[edges[j].A]-edges[j].c)*edges[j].r;
if(d[edges[j].B] < t)
d[edges[j].B] = t;
}
}
for(int j=0;j<num_edges;++j)
if(d[edges[j].B] < (d[edges[j].A]-edges[j].c)*edges[j].r)
return true;
return false;
}
int main(){
cin>>N>>M>>S>>v;
int a,b;
double rab,cab,rba,cba;
for(int i=0;i<M;++i){
cin>>a>>b>>rab>>cab>>rba>>cba;
edges[num_edges].A = a;
edges[num_edges].B = b;
edges[num_edges].r = rab;
edges[num_edges].c = cab;
++num_edges;
edges[num_edges].A = b;
edges[num_edges].B = a;
edges[num_edges].r = rba;
edges[num_edges].c = cba;
++num_edges;
}
if(bellman())
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
return 0;
}