题解
假设答案为ans,转化为
。所以对于每条边,建边w[i] - ans,根据是否有负环进行二分求解即可。
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 5;
const int INF = 0x3f3f3f3f;
struct Edge
{
int from, to; double dist; //起点,终点,距离
Edge(int u, int v, double w):from(u), to(v), dist(w) {}
};
struct SPFA
{
int n, m; //结点数,边数(包括反向弧)
vector<Edge> edges; //边表。edges[e]和edges[e^1]互为反向弧
vector<int> G[MAXN]; //邻接表,G[i][j]表示结点i的第j条边在edges数组中的序号
bool vis[MAXN]; //是否在走过
double d[MAXN]; //spfa
int p[MAXN]; //上一条弧
bool flag; //有没有负环
void init(int n)
{
flag = false;
this->n = n;
edges.clear();
for (int i = 0; i <= n; i++) G[i].clear();
}
void AddEdge(int from, int to, double dist)
{
edges.push_back(Edge(from, to, dist));
m = edges.size();
G[from].push_back(m - 1);
}
void dfs(int u)//spfa
{
vis[u] = true;
for (int i = 0; i < G[u].size(); i++)
{
Edge& e = edges[G[u][i]];
if (d[e.to] > d[u] + e.dist)
{
if (vis[e.to]) { flag = 1; break ; }
d[e.to] = d[u] + e.dist;
p[e.to] = G[u][i];
dfs(e.to);
}
}
vis[u] = false;
}
bool spfa(int s)
{
//memset(d, INF, sizeof(d));
memset(d, 0, sizeof(d));
memset(vis, 0, sizeof(vis));
//dfs(s);
for (int i = 1; i <= n; i++)//起点不固定
{
dfs(i);
if (flag) return false;//有负环
}
return true;//无负环
}
}solve;
const double eps = 1e-10;
int n, m;
vector<Edge> G;
bool check(double x)
{
solve.init(n);
for (int i = 0; i < m; i++)
{
int u = G[i].from, v = G[i].to;
double w = G[i].dist - x;
solve.AddEdge(u, v, w);
}
return solve.spfa(0);
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++)
{
int u, v; double w; scanf("%d%d%lf", &u, &v, &w);
G.push_back(Edge(u, v, w));
}
double l = -1e7, r = 1e7;
while (r-l > eps)
{
double mid = (l+r)/2;
if (check(mid)) l = mid;
else r = mid;
}
printf("%.8f\n", l);
return 0;
}
/*
4 5
1 2 5
2 3 5
3 1 5
2 4 3
4 1 3
*/