题意很简明吧?
枚举的矩形下边界和右端点即右下角,来确定矩形位置;
每一个纵列开一个单调队列,记录从 i-n+1 行到 i 行每列的最大值和最小值,矩形下边界向下推移的时候维护一下;
然后在记录的每一列的最大值和最小值上,跑滑动窗口,即用单调队列维护区间 [ j-n+1 , j ] 的最大值和最小值;
相当于维护了一个矩形的最大值和最小值
#include<cstdio> #include<iostream> #include<queue> #define R register int using namespace std; inline int g() { R ret=0,fix=1; register char ch; while(!isdigit(ch=getchar())) fix=ch=='-'?-1:fix; do ret=ret*10+(ch^48); while(isdigit(ch=getchar())); return ret*fix; } inline int abs(int x) {return x>0?x:-x;} int a,b,n,ans=0x3f3f3f3f; int vl[1010][1010]; deque<int> q[1010],qq[1010],p,pp; signed main() { a=g(),b=g(),n=g(); for(R i=1;i<=a;++i) for(R j=1;j<=b;++j) vl[i][j]=g(); for(R i=1;i<=a;++i) { for(R j=1;j<=b;++j) { while(q[j].size()&&vl[q[j].back()][j]<vl[i][j]) q[j].pop_back(); while(q[j].size()&&q[j].front()+n<=i) q[j].pop_front(); q[j].push_back(i); //cout<<i<<"hang"<<j<<"lie"<<vl[i][q[j].front()]<<" "; //cout<<"mx"<<vl[q[j].front()][j]<<" "; } for(R j=1;j<=b;++j) { while(qq[j].size()&&vl[qq[j].back()][j]>vl[i][j]) qq[j].pop_back(); while(qq[j].size()&&qq[j].front()+n<=i) qq[j].pop_front(); qq[j].push_back(i); //cout<<"mn"<<vl[qq[j].front()][j]<<" "; }//cout<<' '; if(i<n) continue; p.clear();pp.clear(); for(R j=1;j<=b;++j) { while(p.size()&&vl[q[p.back()].front()][p.back()]<vl[q[j].front()][j]) p.pop_back(); while(p.size()&&p.front()+n<=j) p.pop_front(); p.push_back(j); while(pp.size()&&vl[qq[pp.back()].front()][pp.back()]>vl[qq[j].front()][j]) pp.pop_back(); while(pp.size()&&pp.front()+n<=j) pp.pop_front(); pp.push_back(j); if(j<n) continue; ans=min(abs(vl[q[p.front()].front()][p.front()]-vl[qq[pp.front()].front()][pp.front()]),ans); } }printf("%d ",ans); }
2019.04.06