
Description
FJ has, at great expense, surveyed his square farm of N x N hectares (1 <= N <= 250). Each hectare has an integer elevation (0 <= elevation <= 250) associated with it.
FJ will present your program with the elevations and a set of K (1 <= K <= 100,000) queries of the form "in this B x B submatrix, what is the maximum and minimum elevation?". The integer B (1 <= B <= N) is the size of one edge of the square cornfield and is a constant for every inquiry. Help FJ find the best place to put his cornfield.
Input
* Lines 2..N+1: Each line contains N space-separated integers. Line 2 represents row 1; line 3 represents row 2, etc. The first integer on each line represents column 1; the second integer represents column 2; etc.
* Lines N+2..N+K+1: Each line contains two space-separated integers representing a query. The first integer is the top row of the query; the second integer is the left column of the query. The integers are in the range 1..N-B+1.
Output
Sample Input
5 3 1
5 1 2 6 3
1 3 5 2 7
7 2 4 6 1
9 9 8 6 5
0 6 9 3 9
1 2
Sample Output
5
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
using namespace std;
unsigned char dpi[][][],dpa[][][];
int main()
{
int n,b,k;
int i,j,ii,jj,x,y;
unsigned char maxa,mina;
scanf("%d%d%d",&n,&b,&k);
memset(dpi,,sizeof(dpi));
memset(dpa,,sizeof(dpa));
for(i=; i<n; i++)
for(j=; j<n; j++)
scanf("%d",&x),dpa[i][j][]=x,dpi[i][j][]=dpa[i][j][];
for(ii=; ii<; ii++)
{
for(i=; i+(<<ii) - <n; i++)
{
for(j=; j+(<<ii)-<n; j++)
{
dpi[i][j][ii]=min(dpi[i][j][ii-],dpi[i+(<<(ii-))][j][ii-]);
dpi[i][j][ii]=min(dpi[i][j][ii],dpi[i][j+(<<(ii-))][ii-]);
dpi[i][j][ii]=min(dpi[i][j][ii],dpi[i+(<<(ii-))][j+(<<(ii-))][ii-]);
dpa[i][j][ii]=max(dpa[i][j][ii-],dpa[i+(<<(ii-))][j][ii-]);
dpa[i][j][ii]=max(dpa[i][j][ii],dpa[i][j+(<<(ii-))][ii-]);
dpa[i][j][ii]=max(dpa[i][j][ii],dpa[i+(<<(ii-))][j+(<<(ii-))][ii-]);
}
}
}
int kk=log(1.0*b)/log(2.0);
for(i=; i<k; i++)
{
scanf("%d%d",&x,&y);
x--,y--;
maxa=dpa[x][y][kk];
maxa=max(maxa,dpa[x][y+b-(<<kk)][kk]);
maxa=max(maxa,dpa[x+b-(<<kk)][y][kk]);
maxa=max(maxa,dpa[x+b-(<<kk)][y+b-(<<kk)][kk]); mina=dpi[x][y][kk];
mina=min(mina,dpi[x][y+b-(<<kk)][kk]);
mina=min(mina,dpi[x+b-(<<kk)][y][kk]);
mina=min(mina,dpi[x+b-(<<kk)][y+b-(<<kk)][kk]);
printf("%d\n",maxa-mina);
}
}