1047: [HAOI2007]理想的正方形 二维单调队列维护最值

类似滑动的窗口那题,只是这个成了二维,依然单调队列维护就好了。
维护每一列的单调队列,再维护每一行的单调队列,具体实现看代码吧。
(这题我代码写的很丑。。)

#include<iostream>
#include<cstdio>
#define inf 1000000007
using namespace std;
int a[1005][1005],mx1[1005][1005],mn1[1005][1005],mx2[1005][1005],mn2[1005][1005];
struct node{int v,id;} q[1005];
int n,m,k,ans=inf;
inline int read()
{
    int a=0,f=1; char c=getchar();
    while (c<'0'||c>'9') {if (c=='-') f=-1; c=getchar();}
    while (c>='0'&&c<='9') {a=a*10+c-'0'; c=getchar();}
    return a*f;
}
int main()
{
    n=read(); m=read(); k=read();
    for (int i=1;i<=n;i++)
        for (int j=1;j<=m;j++)
            a[i][j]=read();
    for (int j=1;j<=m;j++)
    {
        int l=1,r=0;
        for (int i=1;i<=n;i++)
        {
            while (l<=r&&q[r].v<a[i][j]) r--;
            q[++r]=(node){a[i][j],i};
            if (q[l].id<i-k+1&&l<=r) l++;
            mx1[i][j]=q[l].v;
        }
    }
    for (int j=1;j<=m;j++)
    {
        int l=1,r=0;
        for (int i=1;i<=n;i++)
        {
            while (l<=r&&q[r].v>a[i][j]) r--;
            q[++r]=(node){a[i][j],i};
            if (q[l].id<i-k+1&&l<=r) l++;
            mn1[i][j]=q[l].v;
        }
    }
    for (int i=1;i<=n;i++)
    {
        int l=1,r=0;
        for (int j=1;j<=m;j++)
        {
            while (l<=r&&q[r].v<mx1[i][j]) r--;
            q[++r]=(node){mx1[i][j],j};
            if (q[l].id<j-k+1&&l<=r) l++;
            mx2[i][j]=q[l].v;
        }
    }
    for (int i=1;i<=n;i++)
    {
        int l=1,r=0;
        for (int j=1;j<=m;j++)
        {
            while (l<=r&&q[r].v>mn1[i][j]) r--;
            q[++r]=(node){mn1[i][j],j};
            if (q[l].id<j-k+1&&l<=r) l++;
            mn2[i][j]=q[l].v;
        }
    }
    for (int i=k;i<=n;i++)
        for (int j=k;j<=m;j++)
            ans=min(ans,mx2[i][j]-mn2[i][j]);
    cout << ans;
    return 0;
}

你可能感兴趣的:(1047: [HAOI2007]理想的正方形 二维单调队列维护最值)