分数规划 最短路
和这道题几乎一样。二分后跑负权环即可。
这里我学了一下DFS版SPFA,这个东西判负环很好用。其实就是把队列扩展转化成栈扩展。
代码:
#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 3005
#define M 10005
#define F inline
using namespace std;
typedef double DB;
struct edge{ int next,to; DB d,z; }ed[M];
int n,m,k,h[N]; DB d[M]; bool f[N],fl;
F int _read(){
int x=0; char ch=getchar();
while (!isdigit(ch)) ch=getchar();
while (isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=getchar();
return x;
}
#define addedge(x,y,z) ed[++k]=(edge){h[x],y,z,z},h[x]=k
void spfa(int x){
f[x]=true;
for (int i=h[x],v;i;i=ed[i].next)
if (d[x]+ed[i].z<d[v=ed[i].to])
if (f[v]) { fl=true; break; }
else d[v]=d[x]+ed[i].z,spfa(v);
f[x]=false;
}
F bool pd(DB mid){
memset(d,0,sizeof(d));
memset(f,false,sizeof(f)),fl=false;
for (int i=1;i<=m;i++) ed[i].z=ed[i].d-mid;
for (int i=1;i<=n;i++){
spfa(i); if (fl) return true;
}
return false;
}
int main(){
n=_read(),m=_read();
for (int i=1,x,y;i<=m;i++){
DB z; x=_read(),y=_read();
scanf("%lf",&z),addedge(x,y,z);
}
DB l=-1e9,r=1e9,mid;
while (r-l>1e-9)
if (pd(mid=(l+r)/2)) r=mid; else l=mid;
return printf("%.8f\n",r),0;
}