1. 程式人生 > >HDU 3666 THE MATRIX PROBLEM(差分約束) 題解

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".

Sample Input

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

Sample Output

YES

Source

Recommend

lcy

解題思路:

      題目大概就是給你一個矩陣,然後可以問你n個數ai,和m個數bj,使s【i】【j】*ai/bi在l到r之間,好像有別的方法,不過我只會取log,差分約束跑spfa, 

 L<=m[i][j]*a[i]/b[j]<=U

    log(L/m[i][j])<=log(a[i])-log(b[j])<=log(U/m[i][j])

則 :

    log(a[i])<=log(b[j])+log(U/m[i][j])

    log(b[j])<=log(a[i])+log(m[i][j]/L)

建邊就是根據不等式了,

差分約束題型分析,   求最大值,化為a-b<=c,建b到a的邊權為c的邊,求最短路;   求最小值,化為a-b>=c,建b到a的邊權為c的邊,求最長路;   存在負環,無解;最短路判負環,最長路判正環   求不出最短路,則有任意解;

還有就是這題正常做會tle,所以玄學的把入隊次數改成sqrt(n)就過了;

程式碼:

#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <queue>
#include <stack>
#include <cmath>
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;
const int  maxn=16*1e4+10;

struct newt
{
	int to,next;
	double cost;
}e[maxn*2];
int n,m,head[1000],cnt,cs[1000],vis[1000];
void addedge(int u,int v,double w)
{
	e[cnt].to=v;
	e[cnt].next=head[u];
	e[cnt].cost=w;
	head[u]=cnt++;
}

double dis[1000];
double l,r;
bool spfa()
{
	for(int i=1;i<=n+m;i++)
	dis[i]=1e9,vis[i]=0;
	//memset(vis,0,sizeof(vis));
	queue<int>q;
	vis[1]=1;
	q.push(1);
	cs[1]=1;
	dis[1]=0;
	int t=(int)sqrt((m+n)*1.0);
	while(!q.empty())
	{
		int now=q.front();
		q.pop();
		vis[now]=0;
		for(int i=head[now];i!=-1;i=e[i].next)
		{
			int v=e[i].to;
			if(dis[v]>dis[now]+e[i].cost)
			{
				dis[v]=dis[now]+e[i].cost;
				if(vis[v])continue;
				vis[v]=1;
				if(++cs[v]>t)return 0;
				q.push(v);
				//if(cs[v]>t)return 0;
			}
		}
	}
	return 1;
}
int main()
{
	while(scanf("%d%d%lf%lf",&n,&m,&l,&r)!=EOF)
	{
		double c;cnt=0;
		memset(cs,0,sizeof(cs));
		l=log(l);r=log(r);
		memset(head,-1,sizeof(head));
		for(int i=1;i<=n;i++)
		for(int j=1;j<=m;j++)
		{
			scanf("%lf",&c);
			c=log(c);
			addedge(i,j+n,c-l);
			addedge(j+n,i,r-c);
		}
		if(spfa())puts("YES");
		else puts("NO");
	}
	return 0;
}