题目:
http://poj.org/problem?id=3621
题解:
二分答案,检查有没有负环
#include<cstdio> #include<algorithm> #include<cstring> #define N 1005 using namespace std; struct node { int nxt,v; double w; }e[N*5]; int head[N],ecnt,L,P; double dis[N],fun[N],l,r,mid; bool vis[N]; void add(int u,int v,int w) { e[++ecnt].v=v;e[ecnt].w=w;e[ecnt].nxt=head[u];head[u]=ecnt; } bool spfa_dfs(int u,double val) { vis[u]=1; for (int i=head[u],v;i;i=e[i].nxt) { if (dis[v=e[i].v]>dis[u]+e[i].w*val-fun[u]) { dis[v]=dis[u]+e[i].w*val-fun[u]; if (!vis[v]) {if (spfa_dfs(v,val)) return 1;} else return 1; } } vis[u]=0; return 0; } bool check(double mid) { memset(vis,0,sizeof(vis)); memset(dis,0,sizeof(dis)); for (int i=1;i<=L;i++) if (spfa_dfs(i,mid)) return 1; return 0; } int main() { scanf("%d%d",&L,&P); for (int i=1;i<=L;i++) scanf("%lf",&fun[i]),r+=fun[i]; for (int i=1,u,v,c;i<=P;i++) scanf("%d%d%d",&u,&v,&c),add(u,v,c); for (int i=1;i<=50;i++) { mid=(l+r)/2.0; if (check(mid)) l=mid; else r=mid; } printf("%.2f ",l); return 0; }