思路:
spfa求最长路,cnt[i]记录从s到达i点的路径上点的数量,
当到达某个点路径的点数cnt[i]大于n时,代表在求最长路时用到了正环从而得出有正环。
代码:
#include <iostream>
#include <queue>
#include <cstring>
#include <vector>
#define fastio ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
#define debug(a) cout << "debug : " << (#a) << " = " << a << endl
using namespace std;
typedef long long ll;
typedef pair<ll, ll> PII;
const int N = 110;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int mod = 998244353;
int n, m, s;
double money;
int cnt[N]; //cnt[i]记录从s到达i点的路径上点的数量
bool vis[N];
vector<int> a[N];
double rate[N][N], cost[N][N], dis[N]; //rate为汇率,cost为手续费
bool spfa()
{
memset(dis, 0, sizeof dis);
memset(vis, false, sizeof vis);
memset(cnt, 0, sizeof cnt);
dis[s] += money;
queue<int> q;
cnt[s] = 1;
//从s开始可能不会经过负环,所以一开始要先将所有点加入队列
for (int i = 1; i <= n; i++)
{
q.push(i);
vis[i] = true;
}
while (q.size())
{
int t = q.front();
q.pop();
vis[t] = false; //标记t点出队列
for (int i = 0; i < a[t].size(); i++)
{
int j = a[t][i];
if (dis[j] < (dis[t] - cost[t][j]) * rate[t][j])
{
dis[j] = (dis[t] - cost[t][j]) * rate[t][j];
cnt[j] = cnt[t] + 1;
if (cnt[j] > n)
return true;
if (!vis[j])
{
q.push(j);
vis[j] = true;
}
}
}
}
return false;
}
int main()
{
while (cin >> n >> m >> s >> money)
{
memset(rate, 0, sizeof rate), memset(cost, 0, sizeof cost);
for (int i = 0; i < N; i++)
a[i].clear();
for (int i = 1; i <= m; i++)
{
int x, y;
cin >> x >> y;
a[x].push_back(y), a[y].push_back(x);
cin >> rate[x][y] >> cost[x][y] >> rate[y][x] >> cost[y][x];
}
if (spfa())
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}