其他分享
首页 > 其他分享> > luogu P2216 [HAOI2007]理想的正方形

luogu P2216 [HAOI2007]理想的正方形

作者:互联网

二维RMQ问题模板。。。(虽然我用单调队列加一维RMQ过的,,,但这个更方便一些,就再拿出来写写。。跑的还快一点。。)

和一维差不多,只不过需要比较四个区域罢了。。

g[i][j][k]=max(g[i][j][k-1],max(g[i+(1<<(k-1))][j][k-1],max(g[i][j+(1<<(k-1))][k-1],g[i+(1<<(k-1))][j+(1<<(k-1))][k-1])));

额,就是这样。。

上代码。

#include<iostream>
#include<cstdio>
#include<climits>
#include<cmath>
using namespace std;
int a,b,n,t[1010][1010],g[1050][1050][11],h[1050][1050][11],lg;
int ans=INT_MAX;
inline int read(){
    char c=getchar();int x=0,flag=1;
    while(c<'0' || c>'9'){if(c=='-') flag=-1;c=getchar();}
    while(c>='0' && c<='9') x=(x<<1)+(x<<3)+c-'0',c=getchar();
    return x*flag;
}
int main(){
    a=read();b=read();n=read();
    for(int i=1;i<=a;i++) for(int j=1;j<=b;j++) t[i][j]=read(),g[i][j][0]=h[i][j][0]=t[i][j];
    for(int k=1;k<=10;k++){
        for(int i=1;i+(1<<k)-1<=a;i++){
            for(int j=1;j+(1<<k)-1<=b;j++){
                g[i][j][k]=max(g[i][j][k-1],max(g[i+(1<<(k-1))][j][k-1],max(g[i][j+(1<<(k-1))][k-1],g[i+(1<<(k-1))][j+(1<<(k-1))][k-1])));
                h[i][j][k]=min(h[i][j][k-1],min(h[i+(1<<(k-1))][j][k-1],min(h[i][j+(1<<(k-1))][k-1],h[i+(1<<(k-1))][j+(1<<(k-1))][k-1])));
            }
        }
    }
    lg=log(n)/log(2);
    for(int i=1;i+n-1<=a;i++){
        for(int j=1;j+n-1<=b;j++){
            int MAX=max(g[i][j][lg],max(g[i+n-1-(1<<lg)+1][j][lg],max(g[i][j+n-1-(1<<lg)+1][lg],g[i+n-1-(1<<lg)+1][j+n-1-(1<<lg)+1][lg])));
            int MIN=min(h[i][j][lg],min(h[i+n-1-(1<<lg)+1][j][lg],min(h[i][j+n-1-(1<<lg)+1][lg],h[i+n-1-(1<<lg)+1][j+n-1-(1<<lg)+1][lg])));
            ans=min(ans,MAX-MIN);
        }
    }
    printf("%d\n",ans);return 0;
}

 

标签:1050,RMQ,int,luogu,HAOI2007,while,P2216,include,getchar
来源: https://www.cnblogs.com/SyhAKIOI/p/11706753.html