负环 : 01分数规划
\(求负环 + 01分数规划\)
思路
\(将点权算入边权:\)
\[\begin{aligned}
&\frac{\sum{f_i}}{\sum{w_i}}>mid\\
\Rightarrow\ &\sum{f_i}-\sum{w_i}*mid>0\\
\Rightarrow\ &\sum{(f_i-mid*w_i)}>0
\end{aligned}
\]
\(将每条边的边权转化成f_i-mid*w_i,于是问题转化成求正环.\)
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 1010, M = 5010;
int n, m;
int wf[N];
int h[N], e[M], w[M], ne[M], idx;
double dist[N];
int q[N], cnt[N];
bool st[N];
void add(int a, int b, int c) {
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
bool check(double mid) {
memset(st, 0, sizeof st);
memset(cnt, 0, sizeof cnt);
int hh = 0, tt = 0;
for (int i = 1; i <= n; ++i) {
q[tt++] = i;
st[i] = true;
}
while (hh != tt) {
int t = q[hh++];
if (hh == N) hh = 0;
st[t] = false;
for (int i = h[t]; ~i; i = ne[i]) {
int j = e[i];
if (dist[j] < dist[t] + wf[t] - mid * w[i]) {
dist[j] = dist[t] + wf[t] - mid * w[i];
cnt[j] += 1;
if (cnt[j] >= n) return true;
if (!st[j]) {
q[tt++] = j;
if (tt == N) tt = 0;
st[j] = true;
}
}
}
}
return false;
}
int main() {
IO;
cin >> n >> m;
for (int i = 1; i <= n; ++i) cin >> wf[i];
memset(h, -1, sizeof h);
for (int j = 0; j < m; ++j) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
double l = 0, r = 1e6;
while (r - l > 1e-4) {
double mid = (l + r) / 2;
if (check(mid)) l = mid;
else r = mid;
}
printf("%.2lf\n", l);
return 0;
}