传送门
同 AcWing 361 观光奶牛、洛谷 P2868 [USACO07DEC]Sightseeing Cows G
设 (frac{sum f[i]}{sum t[i]}) 极大值为 (μinleft(0,1000 ight]),采用二分搜索答案方法不断枚举 (mid),
若 (frac{sum f[i]}{sum t[i]}>mid) 即 (sum f[i]-mu*sum t[i]=sum left(f[i]-mid imes t[i] ight)>0) 成立即图中存在正环,
则二分后一半区间,反之二分前一半区间。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef pair<int, int> p;
const double pi(acos(-1));
const int inf(0x3f3f3f3f);
const int mod(1e9 + 7);
const int maxn(1e3 + 10);
const int maxm(6e3 + 10);
bool vis[maxn];
int ecnt, head[maxn], f[maxn], cnt[maxn];
double dis[maxn];
struct edge {
int to, wt, nxt;
} edges[maxm];
template<typename T>
inline const T read()
{
T x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = (x << 3) + (x << 1) + ch - '0';
ch = getchar();
}
return x * f;
}
template<typename T>
inline void write(T x, bool ln)
{
if (x < 0) {
putchar('-');
x = -x;
}
if (x > 9) write(x / 10, false);
putchar(x % 10 + '0');
if (ln) putchar(10);
}
void addEdge(int u, int v, int w)
{
edges[ecnt].to = v;
edges[ecnt].wt = w;
edges[ecnt].nxt = head[u];
head[u] = ecnt++;
}
bool spfa(int n, double val)
{
for (int i = 1; i <= n; ++i) {
dis[i] = -inf;
cnt[i] = 0;
vis[i] = false;
}
vis[0] = true;
dis[0] = 0;
queue<int> q;
q.push(0);
while (not q.empty()) {
int u = q.front();
q.pop();
vis[u] = false;
for (int i = head[u]; compl i; i = edges[i].nxt) {
int v = edges[i].to, w = edges[i].wt;
if (dis[v] < dis[u] + f[v] - val * w) {
dis[v] = dis[u] + f[v] - val * w;
if (not vis[v]) {
vis[v] = true;
q.push(v);
cnt[v] = cnt[u] + 1;
if (cnt[v] >= n + 1) {
return true;
}
}
}
}
}
return false;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("input.txt", "r", stdin);
#endif
ios::sync_with_stdio(false);
memset(head, -1, sizeof head);
int n = read<int>(), m = read<int>();
for (int i = 1; i <= n; ++i) {
f[i] = read<int>();
}
while (m--) {
int u = read<int>(), v = read<int>(), w = read<int>();
addEdge(u, v, w);
}
for (int i = 1; i <= n; ++i) {
addEdge(0, i, 0);
}
double low = 0, high = 1e3;
while (high - low >= 1e-4) {
double mid = (low + high) / 2;
if (spfa(n, mid)) {
low = mid;
} else {
high = mid;
}
}
printf("%.2f
", low);
return 0;
}