题目概述
有一个 a×b 的整数组成的矩阵,从中找出一个 n×n 的正方形区域,使得该区域所有数中的最大值和最小值的差最小。
解题报告
水博客……解法很多,可以二维ST表,线段树套线段树(雾)……
O(n)
解法好……先按照行做单调队列预处理出每个点向左推
n
个的极值,然后按照列做单调队列求出每个点向上向左推
示例程序
#include<cstdio>
#include<cctype>
#include<algorithm>
using namespace std;
const int maxn=1000,MAXINT=((1<<30)-1)*2+1;
int n,m,K,pic[maxn+5][maxn+5],QX[maxn+5],QN[maxn+5];
int MAX[maxn+5][maxn+5],MIN[maxn+5][maxn+5],ans;
#define Eoln(x) ((x)==10||(x)==13||(x)==EOF)
inline char readc()
{
static char buf[100000],*l=buf,*r=buf;
if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
if (l==r) return EOF;return *l++;
}
inline int readi(int &x)
{
int tot=0,f=1;char ch=readc(),lst='+';
while (!isdigit(ch)) {if (ch==EOF) return EOF;lst=ch;ch=readc();}
if (lst=='-') f=-f;
while (isdigit(ch)) tot=(tot<<3)+(tot<<1)+ch-48,ch=readc();
return x=tot*f,Eoln(ch);
}
int main()
{
freopen("program.in","r",stdin);
freopen("program.out","w",stdout);
readi(n);readi(m);readi(K);ans=MAXINT;
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
readi(pic[i][j]);
for (int i=1;i<=n;i++)
{
int HX=1,TX=0,HN=1,TN=0;
for (int j=1;j<K;j++)
{
while (HX<=TX&&pic[i][QX[TX]]<=pic[i][j]) TX--;
while (HN<=TN&&pic[i][QN[TN]]>=pic[i][j]) TN--;
QX[++TX]=j;QN[++TN]=j;
}
for (int j=K;j<=m;j++)
{
while (HX<=TX&&QX[HX]<=j-K) HX++;
while (HN<=TN&&QN[HN]<=j-K) HN++;
while (HX<=TX&&pic[i][QX[TX]]<=pic[i][j]) TX--;
while (HN<=TN&&pic[i][QN[TN]]>=pic[i][j]) TN--;
QX[++TX]=j;QN[++TN]=j;
MAX[i][j]=pic[i][QX[HX]];MIN[i][j]=pic[i][QN[HN]];
}
}
for (int j=K;j<=m;j++)
{
int HX=1,TX=0,HN=1,TN=0;
for (int i=1;i<K;i++)
{
while (HX<=TX&&MAX[QX[TX]][j]<=MAX[i][j]) TX--;
while (HN<=TN&&MIN[QN[TN]][j]>=MIN[i][j]) TN--;
QX[++TX]=i;QN[++TN]=i;
}
for (int i=K;i<=n;i++)
{
while (HX<=TX&&QX[HX]<=i-K) HX++;
while (HN<=TN&&QN[HN]<=i-K) HN++;
while (HX<=TX&&MAX[QX[TX]][j]<=MAX[i][j]) TX--;
while (HN<=TN&&MIN[QN[TN]][j]>=MIN[i][j]) TN--;
QX[++TX]=i;QN[++TN]=i;
ans=min(ans,MAX[QX[HX]][j]-MIN[QN[HN]][j]);
}
}
return printf("%d\n",ans),0;
}