一个人在一个银行存得有钱,不同的银行有不同的汇率和手续费,他把这些钱转到别的银行,操作是(v - 手续费) * 汇率。问能不能转回来时钱上涨。这无非就是求经过所有路径,看是否存在一条不断上涨的路径,类似于负环,只不过判断条件变了。
判断条件:d[v] < (d[u] - es[i].w2) * es[i].w1;
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <queue>
#define inf 0x3f3f3f3f
using namespace std;
const int maxn = 1005;
double cost;
int n, m, s, t; //n为点数 s为源点
int head[maxn]; //head[from]表示以head为出发点的邻接表表头在数组es中的位置,开始时所有元素初始化为-1
double d[maxn]; //储存到源节点的距离,在Spfa()中初始化
int cnt[maxn];
bool inq[maxn]; //这里inq作inqueue解释会更好,出于习惯使用了inq来命名,在Spfa()中初始化
int nodep; //在邻接表和指向表头的head数组中定位用的记录指针,开始时初始化为0
struct node {
int v, next;
double w1, w2;
}es[100050];
void init() {
for(int i = 1; i <= n; i++) {
d[i] = -inf;
inq[i] = false;
cnt[i] = 0;
head[i] = -1;
}
nodep = 0;
}
void addedge(int from, int to, double weight1, double weight2)
{
es[nodep].v = to;
es[nodep].w1 = weight1;
es[nodep].w2 = weight2;
es[nodep].next = head[from];
head[from] = nodep++;
}
bool spfa()
{
queue<int> que;
d[s] = cost; //s为源点
inq[s] = 1;
que.push(s);
while(!que.empty()) {
int u = que.front();
que.pop();
inq[u] = false; //从queue中退出
//遍历邻接表
for(int i = head[u]; i != -1; i = es[i].next) { //在es中,相同from出发指向的顶点为从head[from]开始的一项,逐项使用next寻找下去,直到找到第一个被输
//入的项,其next值为-1
int v = es[i].v;
if(d[v] < (d[u] - es[i].w2) * es[i].w1) { //松弛(RELAX)操作
d[v] = (d[u] - es[i].w2) * es[i].w1;
if(!inq[v]) { //若被搜索到的节点不在队列que中,则把to加入到队列中去
inq[v] = true;
que.push(v);
if(++cnt[v] > n) {
return true;
}
}
}
}
}
return false;
}
int main()
{
while(cin >> n >> m >> s >> cost) {
init();
int a, b;
double c1, p1, c2, p2;
while(m--) {
cin >> a >> b >> c1 >> p1 >> c2 >> p2;
addedge(a, b, c1, p1);
addedge(b, a, c2, p2);
}
if(spfa())
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}