BZOJ4773 负环(floyd+倍增)

  倍增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;
}

 

posted @ 2018-11-16 23:53  Gloid  阅读(154)  评论(0编辑  收藏