hdu_3666_THE MATRIX PROBLEM

Problem Description

You have been given a matrix CN*M, each element E of CN*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”.

题解

首先,把cij除到两边:l'<=ai/bj<=u',如果差分约束的话,应该是ai-bj的形式,于是可以取对数
log(l')<=log(ai)-log(bj)<=log(u')
把log(ai)和log(bj)看成两个点ai和bj,化成求最短路的形式:dis[ai]-dis[bj]<=log(u'),dis[bj]-dis[ai]<=-log(l')
PASCAL神一般的卡精度,建议写C++。(PASCAL过了的,望给我一份)

代码

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
#include <stack>
#include <queue>
#define min(x,y) x<y?x:y
#define max(x,y) x>y?x:y

using namespace std;

struct arr{
    int x,y,next;
    double w;
}a[400001];

int n,m,nm;
int ls[200001],len[200001],st[200001],v[200001];
double l,u,d[200001];

void add(int u,int v,double z){
    nm++;
    a[nm].x=u; a[nm].y=v; a[nm].w=z;
    a[nm].next=ls[u];
    ls[u]=nm;
}

int spfa(){
    int i,t,x;
    memset(len,0,sizeof(len));
    memset(v,0,sizeof(v));
    memset(st,0,sizeof(st));
    for (i=0;i<=n+m;i++)
        d[i]=2147483647;
    t=1;
    d[0]=0; st[1]=0; v[0]=1;
    while (t){
        x=st[t]; t--;
        v[x]=0;
        i=ls[x];
        while (i!=-1){

            if (d[a[i].y]>d[x]+a[i].w){
                d[a[i].y]=d[x]+a[i].w;
                if (!v[a[i].y]){
                    v[a[i].y]=1;
                    st[++t]=a[i].y;
                    len[a[i].y]++;
                    if (len[a[i].y]>sqrt(1.0*(n+m))) 
                        return 0;
                }
            }
            i=a[i].next;
        }
    }
    return 1;
}

int main(){
    int i,j;
    double x;
    while(scanf("%d%d %lf %lf",&n,&m,&l,&u)!=EOF){
        nm=0;
        memset(ls,-1,sizeof(ls));  
        for (i=1;i<=n+m;i++)
            add(0,i,0.0);
        for (i=1;i<=n;i++)
            for (j=1;j<=m;j++){
                scanf("%lf",&x);
                add(j+n,i,log(u/x));
                add(i,j+n,-log(l/x));
            }
        if (spfa()) puts("YES"); else puts("NO");
    }
}
原文地址:https://www.cnblogs.com/zyx-crying/p/9319538.html