HDU 3666.THE MATRIX PROBLEM 差分约束系统

时间:2023-03-08 17:45:46
HDU 3666.THE MATRIX PROBLEM 差分约束系统

THE MATRIX PROBLEM

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8693    Accepted Submission(s): 2246

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".
Sample Input
3 3 1 6
2 3 4
8 2 6
5 2 9
Sample Output
YES
题意:是否存在数组a,b使得l/G[i][j]<=a[i]/b[j]<=u/G[i][j]
思路:乘除变加减取log,加减边乘除去指数。问题变成log2(l)-log2(G[i][j])<=log2(a[i])-log2(b[j])<=log2(u)-log(G[i][j]),这是差分约束系统是否有解,即最短路求解,是否存在负圈。spfa算法,当所有入队列的次数>2*n,即存在负圈,或者每个点入队列的次数>n,其实>sqrt(n+1)就可以了。
dist[i]表示起点s到i的最短距离,对于<u,v>,则dist[u]+w>=dist[v]。所以dist[v]-diat[u]<=w; 
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<set>
#include<bitset>
#include<map>
#include<queue>
#include<stack>
#include<vector>
using namespace std;
#define bug(x) cout<<"bug"<<x<<endl;
#define PI acos(-1.0)
#define eps 1e-8
typedef long long ll;
typedef pair<int,int> P;
const int N=,M=1e6;
const int inf=0x3f3f3f3f;
const ll mod=1e9+;
const double INF=;
struct edge
{
int from,to;
double w;
int next;
};
int n,m;
edge es[M];
int cut,head[N];
double dist[N];
void init()
{
cut=;
memset(head,-,sizeof(head));
}
void addedge(int u,int v,double w)
{
///cout<<u<<" ** "<<v<<" ** "<<w<<endl;
cut++;
es[cut].from=u,es[cut].to=v;
es[cut].w=w;
es[cut].next=head[u];
head[u]=cut;
}
bool spfa()
{
int cou=;
queue<int>q;
bool inq[N];
for(int i=; i<=n+m+; i++) dist[i]=inf,inq[i]=false;
dist[]=;
q.push();
while(!q.empty())
{
int u=q.front();
q.pop();
inq[u]=false;
if(++cou>*(n+m)) return false;
for(int i=head[u]; i!=-; i=es[i].next)
{
edge e=es[i];
if(dist[e.to]>dist[e.from]+e.w)
{
dist[e.to]=dist[e.from]+e.w;
///cout<<e.from<<" * "<<e.to<<" * "<<dist[e.to]<<endl;
if(!inq[e.to]) q.push(e.to),inq[e.to]=true;
}
}
}
return true;
}
int main()
{
double l,u;
while(scanf("%d%d%lf%lf",&n,&m,&l,&u)!=EOF)
{
init();
for(int i=; i<=n; i++)
{
for(int j=; j<=m; j++)
{
double g;
scanf("%lf",&g);
addedge(i,n+j,log2(g)-log2(l));
addedge(n+j,i,log2(u)-log2(g));
}
}
if(spfa()) puts("YES");
else puts("NO");
}
return ;
}

差分约束