hdu3666差分约束

You have been given a matrix C N*M, each element E of C N*M is positive and no more than 1000, The problem is that if there exist N numbers a1, a2, … an and M numbers b1, b2, …, bm, which satisfies that each elements in row-i multiplied with ai and each elements in column-j divided by bj, after this operation every element in this matrix is between L and U, L indicates the lowerbound and U indicates the upperbound of these elements.

Input

There are several test cases. You should process to the end of file. 
Each case includes two parts, in part 1, there are four integers in one line, N,M,L,U, indicating the matrix has N rows and M columns, L is the lowerbound and U is the upperbound (1<=N、M<=400,1<=L<=U<=10000). In part 2, there are N lines, each line includes M integers, and they are the elements of the matrix. 
 

Output

If there is a solution print "YES", else print "NO".

Sample Input

3 3 1 6
2 3 4
8 2 6
5 2 9

Sample Output

YES
 

L<=num[i][j]*a[i ]/b[j]<=U,转化为L/num[i][j]<=log(a[i])-log(b[j])<=U/num[i][j],差分约束即可

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define inf 0x3f3f3f3f
#include<queue>
#define maxn 1005
#define maxm 500005
using namespace std;
struct edge
{
    int next,v;
    double w;
}edges[2*maxm];
int head[maxn];
int vis[maxn];
int num[maxn];
double dis[maxn];
int cnt;
int n,m,l,u;
void init()
{
    memset(head,-1,sizeof(head));
    cnt=0;
}
void addedge(int u,int v,double w)
{
    edges[cnt].v=v;
    edges[cnt].w=w;
    edges[cnt].next=head[u];
    head[u]=cnt++;
}
int spfa()
{memset(vis,0,sizeof(vis));
    memset(num,0,sizeof(num));
    queue<int>q;
    for(int i=0;i<=maxn;i++)
        dis[i]=inf;
        while(!q.empty())
            q.pop();
    vis[1]=1;
    dis[1]=0;
    num[1]=1;
    q.push(1);
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        vis[u]=0;
        num[u]++;
        if(num[u]>sqrt((n+m)))
            return 0;
        for(int i=head[u];i!=-1;i=edges[i].next)
        {
            int v=edges[i].v;
            double w=edges[i].w;
            if(dis[v]>dis[u]+w)
             {

        dis[v]=dis[u]+w;
            if(!vis[v])
            {
                vis[v]=1;
                q.push(v);
            }
        }
    }
    }
    return 1;
}
int main()
{
    while(~scanf("%d%d%d%d",&n,&m,&l,&u))
    {init();
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
        {
            int x;
            scanf("%d",&x);
            double p=log(1.0*l/x);
            double q=log(1.0*u/x);
            addedge(j+n,i,q);
            addedge(i,j+n,-p);
        }
        if(spfa())
            printf("YES\n");
        else
            printf("NO\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sdauguanweihong/article/details/88087858