/**************************************************************
Problem: 1486
User: mogu
Language: C++
Result: Accepted
Time:152 ms
Memory:1896 kb
****************************************************************/
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <vector>
#include <queue>
#include <algorithm>
#define ll long long
using namespace std;
const int MAXN = 10000 + 10;
int u[MAXN], v[MAXN];
double w[MAXN];
int n, m;
int read()
{
int 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 * 10 + ch - '0'; ch = getchar();}
return x * f;
}
struct Edge
{
int to, next;double w;
}edge[MAXN<<1];
int tot, head[MAXN];
void addedge(int u, int v, double w)
{edge[tot].to = v;edge[tot].w=w;edge[tot].next=head[u];head[u]=tot++;}
void build(double x)
{
tot = 0; memset(head, -1, sizeof(head));
for(int i=1;i<=m;i++)
{
addedge(u[i], v[i], w[i] - x);
}
}
int vis[MAXN];
double dis[MAXN];
int flag;
bool spfa(int x)
{
vis[x] = 1;
for(int i=head[x];i!=-1;i=edge[i].next)
{
if(dis[edge[i].to] > dis[x] + edge[i].w)
{
if(vis[edge[i].to])
{
return true;
}
else
{
dis[edge[i].to] = dis[x] + edge[i].w;
if(spfa(edge[i].to)) return true;
}
}
}
vis[x] = 0;
return false;
}
bool check(double mid)
{
build(mid);
memset(dis, 0, sizeof(dis));
memset(vis, 0, sizeof(vis));
flag = 0;
for(int i=1;i<=n;i++)
{
if(spfa(i)) return true;
}
return false;
}
int main()
{
n = read(), m = read();
for(int i=1;i<=m;i++)
u[i] = read(), v[i] = read(),scanf("%lf", &w[i]);
double l = -10000000, r = 10000000;
int T = 60;
while(T--)
{
double mid = (l + r) * 0.5;
if(check(mid)) r = mid;
else l = mid;
}
printf("%.8lf\n", l);
return 0;
}
解题思路:
分数规划,二分+spfa判负环