bzoj1047 [HAOI2007]理想的正方形
题目:https://www.lydsy.com/JudgeOnline/problem.php?id=1047
不要想一个矩阵一个矩阵地弄。把行和列单独弄一下就行了。
#include<iostream> #include<cstdio> #include<cstring> using namespace std; const int N=1005; int n,m,k,a[N][N],c1[N][N],c2[N][N],ans=0x7fffffff; int q1[N],h1,t1,q2[N],h2,t2; int main() { scanf("%d%d%d",&n,&m,&k); for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)scanf("%d",&a[i][j]); for(int i=1;i<=n;i++) { h1=1;t1=0;h2=1;t2=0; for(int j=1;j<=m;j++) { while(h1<=t1&&j-q1[h1]>=k)h1++; while(h2<=t2&&j-q2[h2]>=k)h2++; while(h1<=t1&&a[i][j]>=a[i][q1[t1]])t1--;q1[++t1]=j; while(h2<=t2&&a[i][j]<=a[i][q2[t2]])t2--;q2[++t2]=j; c1[i][j]=a[i][q1[h1]];c2[i][j]=a[i][q2[h2]]; } } for(int j=1;j<=m;j++) { h1=1;t1=0;h2=1;t2=0; for(int i=1;i<=n;i++) { while(h1<=t1&&i-q1[h1]>=k)h1++; while(h2<=t2&&i-q2[h2]>=k)h2++; while(h1<=t1&&c1[i][j]>=c1[q1[t1]][j])t1--;q1[++t1]=i; while(h2<=t2&&c2[i][j]<=c2[q2[t2]][j])t2--;q2[++t2]=i; if(i>=k&&j>=k)ans=min(ans,c1[q1[h1]][j]-c2[q2[h2]][j]); } } printf("%d",ans); return 0; }