POJ 1860 Currency Exchange Bellman-Ford算法求单源最短路径并判断是否有正权回路

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<string>
#include<map>
#include<set>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<sstream>
#define ll long long
using namespace std;
const int N_MAX = 100+10;
const int INF = 0x00ffffff;
const double M_DBL_MAX = 1.7976931348623158e+308;
const double M_DBL_MIN = 2.2250738585072014e-308;
/**********************************************************/
struct bank{
  int l,r;
  double rate,cost;
  bank (int a, int b, double c, double d){l=a,r=b,rate=c,cost=d;}
  bank& operator = (const bank& s){
	l=s.l,r=s.r;
	rate=s.rate,cost=s.cost;
	return *this;
  }
  bank (){}
}exchg[N_MAX*2];
int exlen;
int n,m,s;
double v;
double dist[N_MAX];
/**********************************************************/
int min_2 (int x,int y) {return x<y?x:y;}
int max_2 (int x,int y) {return x>y?x:y;}
void swap (int& a, int& b){a^=b;b^=a;a^=b;}
bool bellman_ford ();
/**********************************************************/
int main()
{
  //freopen ("in.txt","r",stdin);
  scanf ("%d %d %d %lf",&n,&m,&s,&v);
  int a,b;
  double rab,cab,rba,cba;
  exlen=0;
  for (int i=0;i<n;i++){
	scanf ("%d %d %lf %lf %lf %lf",&a,&b,&rab,&cab,&rba,&cba);
	exchg[exlen++]=bank (a-1,b-1,rab,cab);
	exchg[exlen++]=bank (b-1,a-1,rba,cba);
  }
  if (bellman_ford ())
	printf ("YES\n");
  else printf ("NO\n");  
  return 0;
}
bool bellman_ford ()
{
  memset (dist,0,sizeof (dist));//为使价值增加,dist初始化为0
  dist[s-1]=v;//设置源点
  for (int k=0;k<n-1;k++){//循环n-1次
	bool flag=false;
	for (int i=0;i<exlen;i++){//遍历exchg中的每条边
	  int x=exchg[i].l, y=exchg[i].r;
	  if (dist[y]<(dist[x]-exchg[i].cost)*exchg[i].rate){//满足条件
		dist[y]=(dist[x]-exchg[i].cost)*exchg[i].rate;
		flag=true;//当没有做这步说明已经得到”最长路径“
	  }
	}
	if (!flag) break;
  }
  for (int i=0;i<exlen;i++)//如果还做这步,说明前面得到的不是最长路径,说明有正权回路
	if (dist[exchg[i].r]<(dist[exchg[i].l]-exchg[i].cost)*exchg[i].rate)
	  return true;
  return false;
}
    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/qq1627218380/article/details/47085409
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞