POJ 1860 currency exchange (Bellman Ford)

Title:

Now there are n types (1-n) of currencies, m cities. In each city, you can change currency a into currency b, with the exchange rate of r. Commission c will be charged first for each time

Now enter n, m, s (representing the type of currency you had in the first place), v (the amount of currency you had)

Input m row

aa, bb, r1, c1, r2, c2 the exchange rate of aa to bb is r1, the Commission is c1, the exchange rate of bb to aa is r2, the Commission is c2

Can you tell me whether there is value increase of money after several times of exchange (i.e. positive power circuit)

Explanation:

In general, we can use Bellman Ford algorithm to judge the positive weight circuit, just change the relaxation operation and initialization

Change from minimum path to maximum path

AC_code:

/*
Algorithm:bellman-ford
Author: anthony1314
Creat Time:
Time Complexity:
*/

#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<set>
#include<stack>
#include<cstring>
#include<cstdio>
//#include<bits/stdc++.h>
#define ll long long
#define maxn 1005
#define mod 1e9 + 7
#define line printf("--------------");
using namespace std;
int n, m, s;
int tot;
double v, dis[105];
struct node {
	int a, b;
	double r, c;
} edge[205];//Structure of edge
bool bellmanford() {
	memset(dis, 0, sizeof(dis));//Initialize to minimum first
	dis[s] = v;
	bool flag;
	for(int i = 1; i < n; i++) {
		flag = false;
		for(int j = 0; j < tot; j++) {
			if(dis[edge[j].b] < (dis[edge[j].a] - edge[j].c) * edge[j].r) { //Relaxation operation
				flag = true;
				dis[edge[j].b] = (dis[edge[j].a] - edge[j].c) * edge[j].r;
			}
		}
		if(!flag) {
			return false;
		}
	}
	for(int i = 0; i < tot; i++) {
		if(dis[edge[i].b] < (dis[edge[i].a] - edge[i].c) * edge[i].r) {
			return true;
		}
	}
	return false;
}
int main() {
	while(cin>>n>>m>>s>>v) {
		tot = 0;
		int aa, bb;
		double r1, c1, r2, c2;
		for(int i = 0; i < m; i++) {
			scanf("%d %d %lf %lf %lf %lf", &aa, &bb, &r1, &c1, &r2, &c2);
			edge[tot].a = aa;
			edge[tot].b = bb;
			edge[tot].r = r1;
			edge[tot++].c = c1;
			edge[tot].a = bb;
			edge[tot].b = aa;
			edge[tot].r = r2;
			edge[tot++].c = c2;
		}
		if(bellmanford()) {
			cout<<"YES"<<endl;
		} else {
			cout<<"NO"<<endl;
		}
	}
	return 0;
}

 

Posted by sujithfem on Sun, 08 Dec 2019 13:57:19 -0800