lightoj 1081 Square Queries (二维rmq,降维)

lightoj 1081 题目链接

题意:和上一道一样,但是由于size变成了500,如果按照之前的做法会tle + mle...

很容易发现,由于是方阵,长宽是相等的,所以有一维是可以省略的。

也就是所谓的降维?

/* ***********************************************
Author :111qqz
Created Time :2016年05月16日 星期一 19时24分26秒
File Name :code/loj/1081.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=501;
int a[N][N];
int dp[N][N][9];
int n,q;

void init_rmq()
{
    for ( int i = 1 ; i <= n ; i++)
	for ( int j = 1 ; j <= n ; j++)
	    dp[i][j][0] = a[i][j];

    for ( int i = 1 ; (1<<i)<= n ; i++)
	for ( int p = 1 ; p + (1<<i)-1 <= n ; p++)
	    for ( int  q = 1 ; q + (1<<i)-1 <= n ; q++)
		dp[p][q][i] = max(max(dp[p][q][i-1],dp[p+(1<<(i-1))][q][i-1]),max(dp[p][q+(1<<(i-1))][i-1],dp[p+(1<<(i-1))][q+(1<<(i-1))][i-1]));



}

int rmq_max(int x1,int y1,int x2,int y2)
{
    int k = 0;
    while (1<<(k+1)<= x2-x1+1) k++;

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

    return max(max(tmp1,tmp2),max(tmp3,tmp4));
}
int main()
{
	#ifndef  ONLINE_JUDGE 
	freopen("code/in.txt","r",stdin);
  #endif

	int T;
	scanf("%d",&T);
	int cas = 0 ;
	while (T--)
	{
	    printf("Case %d:\n",++cas);
	    scanf("%d %d",&n,&q);
	    ms(a,0);
	    for ( int i = 1 ; i <= n ; i++)
		for ( int j = 1 ; j <= n ; j++) scanf("%d",&a[i][j]);
	    
	    init_rmq();
	    
	    while (q--)
	    {
		int x,y,s;
		scanf("%d %d %d",&x,&y,&s);

		printf("%d\n",rmq_max(x,y,x+s-1,y+s-1));
	    }
	}

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