luogu2216 [HAOI2007]理想的正方形

先对于每一行中长度为 n 的列用单调队列搞出它们的最小/大值,再将这些长度为 n 的列想象成点再对行跑一遍

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int a, b, n, r[1005][1005], qwq[1005], qaq[1005], hwq, twq, haq, taq;
//qwq xiao ,qaq da
int hzxz[1005][1005], hzdz[1005][1005];
//hzxz[i][j]: the minist value in n cols which starts from j in row i
int zzxz[1005][1005], zzdz[1005][1005];
int ans=0x3f3f3f3f, t;
int main(){
	cin>>a>>b>>n;
	for(int i=1; i<=a; i++)
		for(int j=1; j<=b; j++)
			scanf("%d", &r[i][j]);
	for(int i=1; i<=a; i++){
		hwq = haq = 1;
		twq = taq = 0;
		for(int j=1; j<=b; j++){
			t = max(1, j-n+1);
			while(hwq<=twq && qwq[hwq]<=j-n)	hwq++;
			while(haq<=taq && qaq[haq]<=j-n)	haq++;
			while(hwq<=twq && r[i][qwq[twq]]>r[i][j])	twq--;
			while(haq<=taq && r[i][qaq[taq]]<r[i][j])	taq--;
			qwq[++twq] = j;
			qaq[++taq] = j;
			hzxz[i][t] = r[i][qwq[hwq]];
			hzdz[i][t] = r[i][qaq[haq]];
		}
	}
	for(int i=1; i<=b-n+1; i++){
		hwq = haq = 1;
		twq = taq = 0;
		for(int j=1; j<=a; j++){
			t = max(1, j-n+1);
			while(hwq<=twq && qwq[hwq]<=j-n)	hwq++;
			while(haq<=taq && qaq[haq]<=j-n)	haq++;
			while(hwq<=twq && hzxz[qwq[twq]][i]>hzxz[j][i])	twq--;
			while(haq<=taq && hzdz[qaq[taq]][i]<hzdz[j][i])	taq--;
			qwq[++twq] = j;
			qaq[++taq] = j;
			zzxz[t][i] = hzxz[qwq[hwq]][i];
			zzdz[t][i] = hzdz[qaq[haq]][i];
		}
	}
	for(int i=1; i<=a-n+1; i++)
		for(int j=1; j<=b-n+1; j++)
			ans = min(ans, zzdz[i][j]-zzxz[i][j]);
	cout<<ans<<endl;
	return 0;
}
posted @ 2018-01-17 16:36  poorpool  阅读(100)  评论(0编辑  收藏  举报