AcWing 1091 理想的正方形
单调队列应用题,和DP好像没什么关系,借鉴一下大佬写的题解
题解原地址
#include<bits/stdc++.h>
using namespace std;
const int N = 1010, INF = 1e9;
int n, m, k;
int minn[N][N], maxn[N][N];
int w[N][N];
int q[N];
int a[N], b[N], c[N], d[N];
int ans = INF;
void get_min(int a[], int f[], int op){
int hh = 0, tt = -1;
for(int i = 1; i <= op; i ++ ){
if(hh <= tt && i - k >= q[hh]) hh ++ ;
while(hh <= tt && a[i] <= a[q[tt]]) tt -- ;
q[ ++ tt] = i;
f[i] = a[q[hh]];
}
}
void get_max(int a[], int f[], int op){
int hh = 0, tt = -1;
for(int i = 1; i <= op; i ++ ){
if(hh <= tt && i - k >= q[hh]) hh ++ ;
while(hh <= tt && a[i] >= a[q[tt]]) tt -- ;
q[ ++ tt] = i;
f[i] = a[q[hh]];
}
}
int main()
{
cin>>n>>m>>k;
for(int i = 1; i <= n; i ++ ){
for(int j = 1; j <= m; j ++ ){
scanf("%d", &w[i][j]);
}
}
for(int i = 1; i <= n; i ++ ){
get_min(w[i], minn[i], m);
get_max(w[i], maxn[i], m);
}
for(int i = k; i <= m; i ++ ){
for(int j = 1; j <= n; j ++ ){
a[j] = minn[j][i];
b[j] = maxn[j][i];
}
get_min(a, c, n);
get_max(b, d, n);
for(int j = k; j <= n; j ++ ) ans = min(ans, d[j] - c[j]);
}
cout<<ans<<endl;
return 0;
}