[bzoj1047][HAOI2007]理想的正方形【单调队列】
【题目链接】
http://www.lydsy.com/JudgeOnline/problem.php?id=1047
【题解】
横着做一遍单调队列得出每个点往右个的最大/最小值。
接下来用之前的结果竖着做一遍单调队列得出每个矩形的最大/最小值。
复杂度
/* --------------
user Vanisher
problem bzoj-1047
----------------*/
# include <bits/stdc++.h>
# define ll long long
# define inf 0x3f3f3f3f
# define N 1010
using namespace std;
int read(){
int tmp=0, fh=1; char ch=getchar();
while (ch<'0'||ch>'9'){if (ch=='-') fh=-1; ch=getchar();}
while (ch>='0'&&ch<='9'){tmp=tmp*10+ch-'0'; ch=getchar();}
return tmp*fh;
}
int n,m,k,mp[N][N],q[N],mx[N][N],mn[N][N],fx[N][N],fn[N][N];
int main(){
n=read(), m=read(), k=read();
for (int i=1; i<=n; i++)
for (int j=1; j<=m; j++)
mp[i][j]=read();
for (int i=1; i<=n; i++){
int pl=1, pr=0;
for (int j=1; j<=k-1; j++){
while (pl<=pr&&mp[i][j]>mp[i][q[pr]]) pr--;
q[++pr]=j;
}
for (int j=k; j<=m; j++){
while (q[pl]<=j-k) pl++;
while (pl<=pr&&mp[i][j]>mp[i][q[pr]]) pr--;
q[++pr]=j;
mx[i][j-k+1]=mp[i][q[pl]];
}
}
for (int i=1; i<=n; i++){
int pl=1, pr=0;
for (int j=1; j<=k-1; j++){
while (pl<=pr&&mp[i][j]<mp[i][q[pr]]) pr--;
q[++pr]=j;
}
for (int j=k; j<=m; j++){
while (q[pl]<=j-k) pl++;
while (pl<=pr&&mp[i][j]<mp[i][q[pr]]) pr--;
q[++pr]=j;
mn[i][j-k+1]=mp[i][q[pl]];
}
}
for (int i=1; i<=m-k+1; i++){
int pl=1, pr=0;
for (int j=1; j<=k-1; j++){
while (pl<=pr&&mx[j][i]>mx[q[pr]][i]) pr--;
q[++pr]=j;
}
for (int j=k; j<=n; j++){
while (q[pl]<=j-k) pl++;
while (pl<=pr&&mx[j][i]>mx[q[pr]][i]) pr--;
q[++pr]=j;
fx[j-k+1][i]=mx[q[pl]][i];
}
}
for (int i=1; i<=m-k+1; i++){
int pl=1, pr=0;
for (int j=1; j<=k-1; j++){
while (pl<=pr&&mn[j][i]<mn[q[pr]][i]) pr--;
q[++pr]=j;
}
for (int j=k; j<=n; j++){
while (q[pl]<=j-k) pl++;
while (pl<=pr&&mn[j][i]<mn[q[pr]][i]) pr--;
q[++pr]=j;
fn[j-k+1][i]=mn[q[pl]][i];
}
}
int ans=inf;
for (int i=1; i<=n-k+1; i++)
for (int j=1; j<=m-k+1; j++)
ans=min(ans,fx[i][j]-fn[i][j]);
printf("%d\n",ans);
return 0;
}