比较自闭的一道题(学习蓝皮书遇见)
0/1分数规划比较好理解。
我们二分出答案。根据0/1分数规划,我们每次判断跑一次SPFA,每次把边权改为
e[i] = e[i] * mid - f[y] (y为边 e[i] 的出点)
则如果出负环,则存在环比值大于mid 则有 ans > mid 于是令 l = mid
如果全为正环,则对于一切环比值均小于mid 则有 ans < mid 于是令 r = mid
对于SPFA判负环:
记录来到i点的次数 cnt[i] 若有:
cnt[i] >= n
则有i点遍历了大于等于n边,即证明了有负环的存在。
另外学习SFPA
ps.本来是想每次跑一遍就重新建一遍图,参考了大佬的博客,发现每次重新计算边权就可以了。
下面是AC代码:
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <cstdio>
#define ll long long
using namespace std;
const int N = 1e4+5;
const int inf = 0x7ffffff;
double f[N];
int ne[N*2], he[N], ver[N*2];
double ew[N];
double d[N];
int v[N], cnt[N];
int n, m;
int tot = 0;
queue<int> q;
struct Node
{
int x, y;
double w;
}ed[N];
void init()
{
memset(ne, 0, sizeof(ne));
memset(v, 0, sizeof(v));
memset(he, 0, sizeof(he));
memset(cnt, 0, sizeof(cnt));
for (int i = 0; i <= n; i++)
d[i] = inf;
while(q.size()) q.pop();
tot = 0;
}
void add(int x, int y, int w)
{
ver[++tot] = y;
ne[tot] = he[x];
he[x] = tot;
ew[tot] = w;
}
bool SP(double mid)
{
while(q.size()) q.pop();
for (int i = 1; i <= n; i++)
{
d[i] = inf;
v[i] = cnt[i] = 0;
}
d[1] = 0.0; v[1] = 1;
q.push(1);
cnt[1]++;
while(q.size())
{
int x = q.front();
q.pop();
v[x] = 0;
for (int i = he[x]; i; i = ne[i])
{
int y = ver[i];
double z = mid * ew[i] - f[y];
if (d[y] > d[x] + z)
{
d[y] = d[x] +z;
if (!v[y])
{
cnt[y]++;
if (cnt[y] >= n) return 1;
v[y] = 1;
q.push(y);
}
}
}
}
return 0;
}
int main()
{
init();
scanf("%d%d", &n, &m);
double r = -1, l = 0;
for (int i = 1; i <= n; i++)
scanf("%lf", &f[i]), r = max(r, f[i]);
for (int i = 0; i < m; i++)
{
int x, y, w;
scanf("%d%d%d", &x, &y, &w);
add(x, y, w);
}
double mid = l;
while((r - l) > 1e-9)
{
//cout << l << " " << mid << " " << r <<endl;
mid = (r + l) / 2;
if (SP(mid)) l = mid;
else r = mid;
}
printf("%.2f\n", mid);
return 0;
}