poj3179 : corral the cows-离散化的巧妙运用

看看就想到了二分答案,然后用前缀和验证一下。

再一看数据:他喵的居然是10000,n*nlogn绝对爆炸。

经过一会儿的思索,我们发现草只分布在最多500个格子里。

那一定有很多很多行和列是没有草的,而我们需要做的就是去掉这些行列,这就是离散化。

(感觉很nb的样子)

这样的话,我们一开始就要存下每个有草的位置,然后排个序,找到每个草的相对位置,建立一个二维矩阵,并对这个矩阵求矩阵前缀和。预处理结束。接下来就是二分答案。对于每个长度,我们枚举正方形左上角的点,然后找到他可以够到的范围,看是否满足条件就行了。

PS:所有的原数据我们都存在了B数组里面,而离散化后的值就是每个数值的相对排序。

#include <bits/stdc++.h>

using namespace std;
const int maxn=10005;
int c,n,x[maxn],y[maxn],b[maxn];
struct node
{
	int x,y;
}a[maxn];int tot=0;
int s[maxn][maxn];
void lisan()
{
	sort(b+1,b+1+tot);
	tot=unique(b+1,b+1+tot)-b-1;
	for(int i=1;i<=n;i++)
	{
		int tx=lower_bound(b+1,b+tot+1,a[i].x)-b;//相同的第一个 
		int ty=lower_bound(b+1,b+tot+1,a[i].y)-b;
		s[tx][ty]++;
	}
	b[++tot]=10001;//
	for(int i=1;i<=tot;i++)
	{
		for(int j=1;j<=tot;j++) s[i][j]=s[i-1][j]+s[i][j-1]-s[i-1][j-1]+s[i][j];
	}
}
int check(int x)
{
	int p=upper_bound(b+1,b+tot+1,b[tot]-x+1)-b-1;
	for(int i=1;i<=p;i++)
	{
		for(int j=1;j<=p;j++)
		{
			int tx=upper_bound(b+1,b+tot+1,b[i]+x-1)-b-1;//相同的最后一个 
            int ty=upper_bound(b+1,b+tot+1,b[j]+x-1)-b-1;
            if(s[tx][ty]-s[i-1][ty]-s[tx][j-1]+s[i-1][j-1]>=c) return true;
		}
	}
	return false;
}
int main()
{
	scanf("%d%d",&c,&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%d%d",&a[i].x,&a[i].y);
		b[++tot]=a[i].x;b[++tot]=a[i].y;
	}
	lisan();
	int l=1,r=10000;int ans=0;
	while(l<=r)
	{
		int mid=(l+r)/2;
		if(check(mid))
		{
			ans=mid;r=mid-1;
		}
		else l=mid+1;
	}
	printf("%d",ans);
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章