一、题目描述
Several currency exchange points are working in our city. Let us suppose that each point specializes in two particular currencies and performs exchange operations only with these currencies. There can be several points specializing in the same pair of currencies. Each point has its own exchange rates, exchange rate of A to B is the quantity of B you get for 1A. Also each exchange point has some commission, the sum you have to pay for your exchange operation. Commission is always collected in source currency.
For example, if you want to exchange 100 US Dollars into Russian Rubles at the exchange point, where the exchange rate is 29.75, and the commission is 0.39 you will get (100 - 0.39) * 29.75 = 2963.3975RUR.
You surely know that there are N different currencies you can deal with in our city. Let us assign unique integer number from 1 to N to each currency. Then each exchange point can be described with 6 numbers: integer A and B - numbers of currencies it exchanges, and real RAB, CAB, RBA and CBA - exchange rates and commissions when exchanging A to B and B to A respectively.
Nick has some money in currency S and wonders if he can somehow, after some exchange operations, increase his capital. Of course, he wants to have his money in currency S in the end. Help him to answer this difficult question. Nick must always have non-negative sum of money while making his operations.
二、思路分析
- 使用bellman-ford算法(bellman-ford算法见另一篇博客->),判断是否有正权回路(正权回路:在这一回路上,顶点的权值能不断增加即能一直进行松弛)。
三、实现代码
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 110;
int n, m, s,idx;
double v;
double dis[N];//表示从s点到其他点最大路径,初始为0
struct E{
int a, b;//每行输入看作两条边进行存储
double r, c;
}e[N*N];
void bellman_ford(){
int flag = 0;//默认没有正环
memset(dis, 0, sizeof(dis));//一种货币=图上的点
dis[s] = v;
for (int i = 0; i < n; i++){
flag = 0;
for (int j = 0; j < idx; j++){
int a = e[j].a, b = e[j].b;
double r = e[j].r, c = e[j].c;
if (dis[b] < (dis[a] - c)*r){
dis[b] = (dis[a] - c)*r;
flag = 1;//有更新
}
}
if (flag == 0)
break;//本轮没有更新,一定没有正环
}
if (flag == 1)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
int main(){
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
//输入
cin >> n >> m >> s >> v;
idx=0;//边的下标
int a, b;//每行输入看作两条边进行存储
double r1, c1, r2, c2;
while (m--){
cin >> a >> b >> r1 >> c1 >> r2 >> c2;
e[idx].a = a; e[idx].b = b; e[idx].r = r1; e[idx++].c = c1;
e[idx].a = b; e[idx].b = a; e[idx].r = r2; e[idx++].c = c2;
}
//处理
bellman_ford();
return 0;
}