poj1860 currency exchange (bellman ford judgment positive ring)

Portal: Click to open the link

The main idea of ​​the title: a city has n currencies, m currency exchange points, you have v money, each exchange point can only exchange two currencies, (A for B or B for A), each exchange has a unique Exchange rate and handling fee, ask you if there is an exchange method to make the original money more.

Idea: At first I thought that a place can only be used once, it seemed a bit difficult, but later I found out that I read the question wrong. In fact, just judge whether the picture given to you has a positive loop or not, and use dis[] to indicate some kind of The amount of currency, and then bellman can judge the positive ring. (The title emphasizes that the original currency must be used at the end, but in fact this is nonsense, because it starts with the original currency, so you must exchange it back after you exchange it out), the positive ring refers to running a circle and the w becomes larger ring.

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<math.h>
#include<cmath>
#include<time.h>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<algorithm>
#include<numeric>
using namespace std;
int n,m,s,num
const int maxn=110;
double V,dis[maxn];
struct edge{
	int u, v;
	double cost,w;
}e[220];
void addv(int a,int b,double ra,double ca){
	e [num] .u = a;
	e [num] .v = b;
	e [num] .cost = ca;
	e [num ++]. w = ra;
}
bool bellman(){
	dis[s]=V;
	for(int i=1;i<n;i++){//松弛n-1次  
	bool flag=false;
		for(int j=0;j<num;j++){
			int u = e [j] .u;
			int v=e[j].v;
			if(dis[v]<(dis[u]-e[j].cost)*e[j].w){
				dis[v]=(dis[u]-e[j].cost)*e[j].w;
				flag=true;
			}
		}
		if(!flag)return false;// If it can't be relaxed for n-1 times, there must be no positive ring
	}
	for(int i=0;i<num;i++){
		if(dis[e[i].v]<(dis[e[i].u]-e[i].cost)*e[i].w)//If the nth time can be relaxed, it means that there is a positive ring
		return true;
	}
	return false;
}
int main(){
	while(scanf("%d%d%d%lf",&n,&m,&s,&V)!=EOF){
	num=0;
	sizeof(dis,0,sizeof(dis));

	while(m--){
		int a,b;
		double ra,ca,rb,cb;
		scanf("%d%d%lf%lf%lf%lf",&a,&b,&ra,&ca,&rb,&cb);
		addv(a,b,ra,ca);
		addv(b,a,rb,cb);
	}
	if(bellman())printf("YES\n");
	else printf("NO\n");
	}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325908575&siteId=291194637