您的位置:首页 > 其它

bzoj 1047 理想的正方形

2015-11-16 10:38 176 查看
利用单调队列维护以i,j为右下角的正方形的两个极值。把w大成h了。
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>

#define md
#define ll long long
#define inf (int) 1e9
#define eps 1e-8
#define N 1010
using namespace std;
int a

,qmx

,qmn

;
struct yts { int dt,pos;} q1
,q2
;
int main()
{
	int A,B,n; 
	scanf("%d%d%d",&A,&B,&n);
	for (int i=1;i<=A;i++)
	  for (int j=1;j<=B;j++)
	    scanf("%d",&a[i][j]);
	for (int j=1;j<=B;j++)
	{
		int h=1,w=0;
		for (int i=1;i<=A;i++)
		{
			while (h<=w&&q1[h].pos<=i-n) h++;
			while (h<=w&&q1[w].dt<=a[i][j]) w--;
			q1[++w].pos=i; q1[w].dt=a[i][j];
			qmx[i][j]=q1[h].dt;
		}
		h=1,w=0;
		for (int i=1;i<=A;i++)
		{
			while (h<=w&&q2[h].pos<=i-n) h++;
			while (h<=w&&q2[w].dt>=a[i][j]) w--;
			q2[++w].pos=i; q2[w].dt=a[i][j];
			qmn[i][j]=q2[h].dt;
		}
	}
	int ans=inf;
	for (int i=n;i<=A;i++)
	{
		int h1=1,w1=0,h2=1,w2=0;
		for (int j=1;j<=B;j++)
		{
			while (h1<=w1&&q1[h1].pos<=j-n) h1++;
			while (h1<=w1&&q1[w1].dt<=qmx[i][j]) w1--;
			q1[++w1].pos=j; q1[w1].dt=qmx[i][j];
			while (h2<=w2&&q2[h2].pos<=j-n) h2++;
			while (h2<=w2&&q2[w2].dt>=qmn[i][j]) w2--;
			q2[++w2].pos=j; q2[w2].dt=qmn[i][j];
			if (j>=n) ans=min(ans,q1[h1].dt-q2[h2].dt);
		}
	}
	printf("%d\n",ans);
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: