hdu 2888 check corners (二维rmq模板题)

Posted by 111qqz on Monday, May 16, 2016

TOC

hdu2888题目链接

题意:问某个矩阵内的最大值,并且问最大值是否是在四个角中出现。 思路:二维rmq.需要注意数组稍微开大1就会MLE,因为是四维数组,一维大一点,整个就会大很多==。

/* ***********************************************
Author :111qqz
Created Time :2016年05月16日 星期一 16时51分00秒
File Name :code/hdu/2888.cpp
************************************************ */

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
#define fst first
#define sec second
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define ms(a,x) memset(a,x,sizeof(a))
typedef long long LL;
#define pi pair < int ,int >
#define MP make_pair

using namespace std;
const double eps = 1E-8;
const int dx4[4]={1,0,0,-1};
const int dy4[4]={0,-1,1,0};
const int inf = 0x3f3f3f3f;
const int N=301;
int n,m,q;
int a[N][N];
int dp[N][N][9][9];


void init_rmq()
{
    for ( int i = 1 ; i <= n ; i++)
    for ( int j = 1; j <= m ; j++) dp[i][j][0][0] = a[i][j];
    
    for ( int i = 0 ; (1<<i)<= n ; i++)
    for ( int j = 0 ; (1<<j)<= m  ;j++)
        if (i==0&&j==0) continue;
        else for ( int p = 1 ; p + (1<<i)-1 <= n ; p++)
              for ( int q = 1 ; q + (1<<j)-1 <= m ;q ++)
              if (i==0)
                  dp[p][q][i][j] = max(dp[p][q][i][j-1],dp[p][q+(1<<(j-1))][i][j-1]);
              else dp[p][q][i][j] = max(dp[p][q][i-1][j],dp[p+(1<<(i-1))][q][i-1][j]);
    
}



int rmq_max(int x1,int y1,int x2,int y2)
{
    int k1 = 0 ;
    int k2 = 0 ;

    while (1<<(k1+1)<=x2-x1+1) k1++;
    while (1<<(k2+1)<=y2-y1+1) k2++;

    int tmp1 = dp[x1][y1][k1][k2];
    int tmp2 = dp[x2-(1<<k1)+1][y1][k1][k2];
    int tmp3 = dp[x1][y2-(1<<k2)+1][k1][k2];
    int tmp4 = dp[x2-(1<<k1)+1][y2-(1<<k2)+1][k1][k2];

    return max(max(tmp1,tmp2),max(tmp3,tmp4));
}

int main()
{
    #ifndef  ONLINE_JUDGE 
    freopen("code/in.txt","r",stdin);
  #endif

    while (scanf("%d %d",&n,&m)!=EOF)
    {
        for ( int i = 1 ; i <= n ; i++)
        for ( int j = 1 ; j <= m ; j++) scanf("%d",&a[i][j]);
        init_rmq();

        scanf("%d",&q);
        while (q--)
        {
        int r1,c1,r2,c2;
        scanf("%d %d %d %d",&r1,&c1,&r2,&c2);
        int ans = rmq_max(r1,c1,r2,c2);
        printf("%d ",ans);
        if (a[r1][c1]==ans||a[r1][c2]==ans||a[r2][c1]==ans||a[r2][c2]==ans)
        {
            puts("yes");
        }
        else
        {
            puts("no");
        }
        }

    }



  #ifndef ONLINE_JUDGE  
  fclose(stdin);
  #endif
    return 0;
}

「真诚赞赏,手留余香」

111qqz的小窝

真诚赞赏,手留余香

使用微信扫描二维码完成支付