会建图,然后使用标准的Bellman Ford算法,判断负环就解决了。
不过本题实际应用不是计算负环,而是计算最大值,也就是求出源点到所有点的最大收益值之后,然后判断是否可以进一步增加收益,如果可以那么证明有环可以不断反复走这个环,不断增加收益,实际就是判负环的应用了。
#include <stdio.h> #include <vector> #include <string.h> #include <algorithm> #include <iostream> #include <string> #include <limits.h> #include <stack> #include <queue> #include <set> #include <map><span style="white-space:pre"> </span> #include <float.h> using namespace std; const int MAX_N = 101; int N, M, Src; double V, dis[MAX_N]; struct Node { int s, d;//source and destination vertex double w, c;//exchange rate and commission }; Node gra[MAX_N<<1]; bool BellmanFord(int src, int n, double val)//n: number of edges { fill(dis, dis+N+1, 0.0); dis[src] = val; for (int i = 1; i < N; i++)//标准Bellman Ford Algorithm { for (int j = 0; j < n; j++) { int u = gra[j].s, v = gra[j].d; if (dis[u] != 0.0) { double t = (dis[u]-gra[j].c) * gra[j].w; if (t > dis[v]) dis[v] = t; } } } for (int j = 0; j < n; j++)//判断负环 { int u = gra[j].s, v = gra[j].d; if (dis[u] != 0.0) { double t = (dis[u] - gra[j].c) * gra[j].w; if (t > dis[v]) return true; } } return false; } int main() { while (scanf("%d %d %d %lf", &N, &M, &Src, &V) != EOF) { int u, v, id = 0; double a, b, c, d; for (int i = 0; i < M; i++) { scanf("%d %d %lf %lf %lf %lf", &u, &v, &a, &b, &c, &d); gra[id].s = u, gra[id].d = v; gra[id].w = a, gra[id].c = b; id++; gra[id].s = v, gra[id].d = u; gra[id].w = c, gra[id].c = d; id++; } if (BellmanFord(Src, id, V)) puts("YES"); else puts("NO"); } return 0; }
时间: 2024-10-03 13:47:05