1. 程式人生 > >BZOJ4773 負環(floyd+倍增)

BZOJ4773 負環(floyd+倍增)

eof 倍增 har turn fine 自身 gcd ostream ++

  倍增floyd求出經過<=2k條邊時兩點間最短路,一個點到自身的最短路就是包含該點的最小環。然後倍增找答案即可。註意初始時到自身的最短路設為0,這樣求出的最短路就是經過<=2k條邊的而不是恰好2k條邊的了。

#include<iostream> 
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define
N 310 char getc(){char c=getchar();while ((c<A||c>Z)&&(c<a||c>z)&&(c<0||c>9)) c=getchar();return c;} int gcd(int n,int m){return m==0?n:gcd(m,n%m);} int read() { int x=0,f=1;char c=getchar(); while (c<0||c>9) {if (c==-) f=-1;c=getchar();}
while (c>=0&&c<=9) x=(x<<1)+(x<<3)+(c^48),c=getchar(); return x*f; } int n,m,a[10][N][N],f[N][N],g[N][N],ans; int main() { #ifndef ONLINE_JUDGE freopen("bzoj4773.in","r",stdin); freopen("bzoj4773.out","w",stdout); const char LL[]="%I64d\n"; #else const
char LL[]="%lld\n"; #endif n=read(),m=read(); memset(a,42,sizeof(a)); while (m--) { int x=read(),y=read(),z=read(); a[0][x][y]=z; } for (int i=1;i<=n;i++) a[0][i][i]=0; for (int t=1;t<10;t++) for (int k=1;k<=n;k++) for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) a[t][i][j]=min(a[t][i][j],a[t-1][i][k]+a[t-1][k][j]); memset(f,42,sizeof(f)); for (int i=1;i<=n;i++) f[i][i]=0; for (int t=9;~t;t--) { memset(g,42,sizeof(g)); for (int k=1;k<=n;k++) for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) g[i][j]=min(g[i][j],f[i][k]+a[t][k][j]); bool flag=1; for (int i=1;i<=n;i++) if (g[i][i]<0) {flag=0;break;} if (flag) memcpy(f,g,sizeof(f)),ans+=1<<t; if (ans>=n) break; } cout<<(ans>=n?0:ans+1); return 0; }

BZOJ4773 負環(floyd+倍增)