ZOJ 1544 Currency Exchange(bellman_ford)

因为货币可以无限的进行兑换,所以只要存在正回路就一定能成功

#include <iostream>
#include <cstdio>
#include <memory.h>
using namespace std;
const int maxn=110;
struct edge{
	int u,v;
	double rate,coms;
}es[maxn*2];
double dis[maxn],V;
int n,m,S;
void addEdge(int idx,int u,int v,double r,double c){
	es[idx].u=u;
	es[idx].v=v;
	es[idx].rate=r;
	es[idx].coms=c;
}
bool bellman_ford(){
	memset(dis,0,sizeof(dis));
	dis[S]=V;
	for (int i=1;i<=n;++i){
		bool f=0;
		for (int j=0;j<m*2;++j){
			int u=es[j].u,v=es[j].v;
			double r=es[j].rate,c=es[j].coms;
			if(dis[v]+1e-5<(dis[u]-c)*r){
				dis[v]=(dis[u]-c)*r;
				f=1;
			}
		}
		if(!f)break;
	}
	for (int j=0;j<m*2;++j){
		int u=es[j].u,v=es[j].v;
		double r=es[j].rate,c=es[j].coms;
		if(dis[v]+1e-5<(dis[u]-c)*r){
			return true;
		}
	}
	return false;
}
int main(){
	while (scanf("%d%d%d%lf",&n,&m,&S,&V)==4){
		for (int i=0;i<m;++i){
			int u,v;
			double a,b,c,d;
			scanf("%d%d%lf%lf%lf%lf",&u,&v,&a,&b,&c,&d);
			addEdge(i*2,u,v,a,b);
			addEdge(i*2+1,v,u,c,d);
		}
		if(bellman_ford()){
			printf("YES\n");
		}else{
			printf("NO\n");
		}
	}
	return 0;
}
    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/zxjcarrot/article/details/8811165
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞