51nod 1340 差分约束

思路:

带未知量的Floyd

很强

http://yousiki.net/index.php/archives/87/

//By SiriusRen
#include <bits/stdc++.h>
using namespace std;
const int B=55;
int cases,n,m1,m2,xx,yy,zz;
typedef long long ll;
ll f[55][55][115],l,r,inf;
void up(ll &x,ll y){x=min(x,y);}
signed main(){
    scanf("%d",&cases);
    while(cases--){
        memset(f,0x3f,sizeof(f));
        scanf("%d%d%d",&n,&m1,&m2),l=n,r=inf=f[0][0][0];
        for(int i=0;i<=n;i++)f[i][i][B]=0,i?f[i][i-1][B]=-1:0;
        up(f[0][n][B+1],0);up(f[n][0][B-1],0);
        for(int i=1;i<=m1;i++)scanf("%d%d%d",&xx,&yy,&zz),up(f[yy][xx][B+(xx>=yy)],-zz);
        for(int i=1;i<=m2;i++)scanf("%d%d%d",&xx,&yy,&zz),up(f[xx][yy][B-(xx>=yy)],zz);
        for(int i=0;i<=n;i++)for(int j=0;j<=n;j++)for(int x=-B;x<=B;x++)if(f[j][i][x+B]<inf)
            for(int k=0;k<=n;k++)for(int y=max(-B,-B-x);y<=B&&x+y<=B;y++)if(f[i][k][y+B]<inf)
                up(f[j][k][x+y+B],f[j][i][x+B]+f[i][k][y+B]);
        for(int i=0;i<=n;i++)for(int j=0;j<=2*B;j++){
            if(j==B){if(f[i][i][j]<0){puts("0");goto be;}}
            else if(f[i][i][j]<inf)j>B?l=max(l,(-f[i][i][j]-1)/(j-B)+1):r=min(r,-f[i][i][j]/(j-B));
        }printf("%lld\n",r==inf?-1:(l<=r?r-l+1:0));be:;
    }
}

 

posted @ 2017-06-19 21:02  SiriusRen  阅读(189)  评论(0编辑  收藏  举报