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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值