01分数规划

例题:spfa求负环 + 01分数规划

可参考如下博客:分数规划

常见形式

  • (一堆和) / (一堆和) 使其结果最大

方法:

  • 二分 [l, r]
  • f的和 / t的和 > mid => f的和 > mid t的和 => (f[i] - mid t[i])的和 > 0
  • 最终 等价于图中是否存在正环?

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

const int N = 1010, M = 5010;

int n, m;
int wf[N];
int h[N], e[M], wt[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, wt[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}

bool check(double mid)
{
memset(dist, 0, sizeof dist);
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 * wt[i])
{
dist[j] = dist[t] + wf[t] - mid * wt[i];
cnt[j] = cnt[t] + 1;
if(cnt[j] >= n) return true;

if(!st[j])
{
st[j] = true;
q[tt ++ ] = j;
if(tt == N) tt = 0;
}
}
}
}

return false;
}

int main()
{
cin >> n >> m;

memset(h, -1, sizeof h);
for (int i = 1; i <= n; i ++ )
cin >> wf[i];

while(m -- )
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}

double l = 0, r = 1010;
while(r - l > 1e-4)
{
double mid = (l + r) /2;
if(check(mid)) l = mid;
else r = mid;
}

printf("%.2f\n", r);

return 0;
}