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

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

题意:给你一个n*m的矩阵,一个L,一个U,问你是否存在数组a[1...n],b[1...m],使得矩阵中每个数Aij,L <= Aij*a[i]/b[j] <= U;

思路:L <= Aij*a[i]/b[j] <= U可得L/Aij <= a[i]/b[j] <= U/Aij,即L/Aij <= a[i]/b[j],与a[i]/b[j] <= U/Aij,由于差分约束系统是x[i]-x[j]>=k的形式,我们要凑出这种形式,我们可以取对数,得log(L/Aij)<= log(a[i])-log(b[j]),与log(a[i])-log(b[j]) <= log(U/Aij)

//为什么判负环时cont[y]>=n+m会T????判负环时cont[y]>=sqrt(n+m)就AC????????????

#include<cstdio>
#include<queue>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=2e5+10;
const int inf=0x3f3f3f3f;
int head[maxn],cont[maxn],book[maxn],cnt,n,m;
double dis[maxn];
struct node{
	int id;
	double val;
	int next;
}side[maxn*4];
void init()
{
	memset(book,0,sizeof(book));
	memset(cont,0,sizeof(cont));
	memset(head,-1,sizeof(head));
	for(int i=0;i<=n*m;i++)
		dis[i]=inf;
	cnt=0;
}
void add(int x,int y,double d)
{
	side[cnt].id=y;
	side[cnt].val=d;
	side[cnt].next=head[x];
	head[x]=cnt++;
}
int SPFA(int sx)
{
	queue<int> q;
	book[sx]=1;
	dis[sx]=0;
	cont[sx]=1;
	q.push(sx);
	while(q.size())
	{
		int x=q.front();
		q.pop();
		book[x]=0;
		for(int i=head[x];i!=-1;i=side[i].next)
		{
			int y=side[i].id;
			if(dis[y]>dis[x]+side[i].val)
			{
				dis[y]=dis[x]+side[i].val;
				if(!book[y])
				{
					book[y]=1;
					cont[y]++;
					if(cont[y]>=sqrt(n+m))
					{
						return 0;
					}
					q.push(y);
				}
			}
		}
	}
	return 1;
}
int main()
{
	int l,u,x;
	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++)
			{
				scanf("%d",&x);
				add(i,j+n,-log((1.0*l)/(1.0*x)));
				add(j+n,i,log((1.0*u)/(1.0*x)));
			}
			add(0,i,0);
		}
		if(SPFA(0))
			printf("YES\n");
		else
			printf("NO\n");
		
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/why932346109/article/details/89104749