二维ST表

· · 个人记录

这个其实没啥用,离线下来暴力做其实就可以。不过介于这是我手推出来的,不忍心删掉(

这里介绍一下二维 ST表处理二维数组中一个子矩阵内的最大/小值。

这里的 \operatorname{mymax()} 函数是返回四个参数中的最大值。

时间复杂度 O(n \times m \log_2 (n \times m))。若 n \times m \leq 10^6 大致可以卡过。

好,上代码:

#include <bits/stdc++.h>
using namespace std;
int f[1005][1005][11][11],lg2[200005];

inline int mymax(const int &a,const int &b,const int &c,const int &d)
{
    return max(max(a,b),max(c,d));
}
int main()
{
    int n,m,q;
    scanf("%d%d%d",&n,&m,&q);
    for(int i=1;i<=200000;i++)
        lg2[i]=lg2[i>>1]+1;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
            scanf("%d",&f[i][j][0][0]);

    for(int i=n;i>=1;i--)
    for(int j=1;j<=m;j++)
    for(int k=1;k<=10;k++)
    for(int l=1;l<=10;l++)
        f[i][j][k][l]=mymax(f[i][j][k-1][l-1],f[i+(1<<k-1)][j][k-1][l-1],f[i][j+(1<<l-1)][k-1][l-1],f[i+(1<<k-1)][j+(1<<l-1)][k-1][l-1]);

    for(int i=1;i<=q;i++)
    {
        int x1,y1,x2,y2;
        scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
        int p1=lg2[x2-x1],p2=lg2[y2-y1];
        printf("%d\n",mymax(f[x1][y1][p1][p2],f[x2-(1<<p1)+1][y1][p1][p2],f[x1][y2-(1<<p2)+1][p1][p2],f[x2-(1<<p1)+1][y2-(1<<p2)+1][p1][p2]));
    }
    return 0;
}

总体来说难度不大。