HDU 3666 (差分约束)

Probelm

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”

题意描述

给出一个 NM N ∗ M 的矩阵 C C ,要求构造两个序列 a1,a2,...,an a 1 , a 2 , . . . , a n b1,b2,...,bm b 1 , b 2 , . . . , b m
矩阵的第 i i 行元素乘上 ai a i ,矩阵的第 j j 列元素除以 bj b j ,最终矩阵的每个元素 Cij[L,U] C i j ∈ [ L , U ]
若可以构造成功,则输出”YES”,否则输出”NO”

题解

依题意

LCijaibjU L ≤ C i j ∗ a i b j ≤ U

对上列式子两边取 log l o g ,得
logLlogCij+logailogbjlogU l o g L ≤ l o g C i j + l o g a i − l o g b j ≤ l o g U

将序列 a,b a , b 整合为一个序列记为 S S
S1...Sn S 1 . . . S n 为原 a a 序列取 log l o g Sn+1...Sn+m S n + 1 . . . S n + m 为原 b b 序列取 log l o g
则上式为
logLlogCij+SiSn+jlogU l o g L ≤ l o g C i j + S i − S n + j ≤ l o g U

故有线性约束条件如下
SiSn+jlogLlogCij S i − S n + j ≥ l o g L − l o g C i j

SiSn+jlogUlogCij S i − S n + j ≤ l o g U − l o g C i j

约束图表示为 w(i,n+j)=logCijL w ( i , n + j ) = l o g C i j L w(n+j,i)=logUCij w ( n + j , i ) = l o g U C i j

代码

#include
using namespace std;

const double inf = 1e9;
const int maxn = 550;
struct node
{
    int to;
    double w;
    node (int i=0,double j=0)
    {
        to = i, w = j;
    }
};
int n,m,l,u,uptimes,cnt[maxn<<1];
double d[maxn<<1];
bool vis[maxn<<1];
vector  g[maxn<<1];

bool spfa()
{
    queue  q;
    q.push(0);
    vis[0] = 1;
    d[0] = 0;
    while (!q.empty())
    {
        int u = q.front();

        for (int i=0;iif (d[v] > d[u]+dis)
            {
                d[v] = d[u]+dis;
                if (!vis[v])
                {
                    vis[v] = 1;
                    q.push(v);
                    if (++cnt[v] > uptimes) return false;
                }
            }

        }

        q.pop();
        vis[u] = 0;
    }
    return true;
}

int main()
{
    while (scanf("%d %d %d %d",&n,&m,&l,&u)!=EOF)
    {
        uptimes = sqrt(n+m);
        for (int i=0;i0;
            d[i] = inf;
        }

        int x;
        for (int i=0;ifor (int j=0;j"%d",&x);
                g[j+n].push_back(node(i,log((double)u/x)));
                g[i].push_back(node(j+n,log((double)x/l)));
            }

        if (spfa()) printf("YES\n");
        else
            printf("NO\n");
    }
    return 0;
}

你可能感兴趣的:(图论,差分约束)