HDU 2888 Check Corners

http://acm.hdu.edu.cn/showproblem.php?pid=2888

二维RMQ。。。

dp[row][col][i][j] 表示[row,row+2^i-1]x[col,col+2^j-1] 二维区间内的最小值

== max( [row,row+ 2^(i-1)-1]x[col,col+2^j-1], [row+2^(i-1),row+2^i-1]x[col,col+2^j-1] )
= max(dp[row][col][i-1][j], dp[row+(1<<(i-1))][col][i-1][j] )
//y轴不变,x轴二分 (i!=0)

== max( [row,row+2^i-1]x[col,col+2^(j-1)-1],  [row,row+2^i-1]x[col+2^(i-1),col+2^j-1] )
= max(dp[row][col][i][j-1], dp[row][col+(1<<(j-1))][i][j-1] ) 
//x轴不变,y轴二分 (j!=0)
即:
dp[row][col][i][j] = max(dp[row][col][i-1][j], dp[row + (1<<(i-1))][col][i-1][j] )   
             或    = max(dp[row][col][i][j-1], dp[row][col+(1<<(j-1))][i][j-1] )
查询[x1,x2]x[y1,y2]
令 kx = (int)log2(x2-x1+1);
   ky = (int)log2(y2-y1+1);
查询结果为
   m1 = dp[x1][y1][kx][ky]                    = dp[x1][y1][kx][ky];
   m2 = dp[x2-2^kx+1][y1][kx]ky]              = dp[x2-(1<<kx)+1][y1][kx][ky];
   m3 = dp[x1][y2-2^ky+1][kx][ky]             = dp[x1][y2-(1<<ky)+1][kx][ky];
   m4 = dp[x2-2^kx+1][y2-2^ky+1][kx][ky]      = dp[x2-(1<<kx)+1][y2-(1<<ky)+1][kx][ky];
结果 = max(m1,m2,m3,m4)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
#define N 302
int dp[N][N][9][9];
int a[N][N];
int n,m;
void init()
{
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
        dp[i][j][0][0]=a[i][j];
    int mx=log(1.0*n)/log(2.0);
    int my=log(m+0.0)/log(2.0);
    for(int i=0;i<=mx;i++)
        for(int j=0;j<=my;j++)
    {
        if(i==0&&j==0) continue;
        for(int row=1;row+(1<<i)-1<=n;row++)
        {
            for(int col=1;col+(1<<j)-1<=m;col++)
            {
                if(i==0)
                    dp[row][col][i][j]=
                    max(dp[row][col][i][j-1],
                        dp[row][col+(1<<(j-1))][i][j-1]);
                else
                    dp[row][col][i][j]=
                    max(dp[row][col][i-1][j],
                        dp[row+(1<<(i-1))][col][i-1][j]);
            }
        }
    }
}
int rmq(int x1,int y1,int x2,int y2)
{
    int kx=log(x2-x1+1.0)/log(2.0);
    int ky=log(y2-y1+1.0)/log(2.0);
    int m1=dp[x1][y1][kx][ky];
    int m2=dp[x2-(1<<kx)+1][y1][kx][ky];
    int m3=dp[x1][y2-(1<<ky)+1][kx][ky];
    int m4=dp[x2-(1<<kx)+1][y2-(1<<ky)+1][kx][ky];
    return max(max(m1,m2),max(m3,m4));
}
int main()
{
   while(scanf("%d%d",&n,&m)!=EOF)  // while(cin>>n>>m&&n)
    {
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
           scanf("%d",&a[i][j]);// cin>>a[i][j];
        int q; cin>>q;
        init();
        while(q--) {
            int x1,y1,x2,y2;
            scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
            int ans=rmq(x1,y1,x2,y2);
            printf("%d ",ans);
            if(ans==a[x1][y1]||ans==a[x2][y1]||ans==a[x1][y2]||ans==a[x2][y2])
                puts("yes");
            else puts("no");
        }
    }
}

参考:http://blog.csdn.net/mishifangxiangdefeng/article/details/7109199

你可能感兴趣的:(HDU 2888 Check Corners)