FJ has decided to grow his own corn hybrid in order to help the cows make the best possible milk. To that end, he’s looking to build the cornfield on the flattest piece of land he can find.
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
-
Line 1: Three space-separated integers: N, B, and K.
-
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 -
Lines 1…K: A single integer per line representing the difference between the max and the min in each query.
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
给一个n* n的矩阵,告诉询问范围是一个b* b的矩阵,有q个询问,每个询问给出要询问的b* b大小的矩阵的左上角,求其中最大值和最小值的差
用二维ST表
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<vector>
#include<cmath>
#define LL long long
#define mem(a, b) memset(a, b, sizeof(a))
#define N 255
#define MOD
using namespace std;
const int inf=0x3f3f3f3f;
int n, b, q, a, f1[N][N][15], f2[N][N][15];
void ST_prework() {
int t=log(n)/log(2);
for(int k=1;k<=n;k++)
{
for(int j=1;j<=t;j++)
{
for(int i=1;i<=n+1-(1<<j);i++)
{
f1[k][i][j]=max(f1[k][i][j-1],f1[k][i+(1<<(j-1))][j-1]);
f2[k][i][j]=min(f2[k][i][j-1],f2[k][i+(1<<(j-1))][j-1]);
}
}
}
}
int ST_query(int l, int r) {
int k=log(b)/log(2);
int ma=0, mi=0x3f3f3f3f;//不能忘
for(int i=l;i<l+b;i++){
ma=max(max(f1[i][r][k],f1[i][(r+b-1)-(1<<k)+1][k]),ma);
mi=min(min(f2[i][r][k],f2[i][(r+b-1)-(1<<k)+1][k]),mi);
}
return ma-mi;
}
int main() {
while(scanf("%d%d%d",&n, &b, &q)!=EOF){
mem(f1, 0); mem(f2, 0);
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++) {
int t;
scanf("%d", &t);
f1[i][j][0]=t, f2[i][j][0]=t;
}
}
ST_prework();
for(int i=1; i<=q; i++) {
int x, y;
scanf("%d%d",&x, &y);
cout<<ST_query(x, y)<<endl;
}
}
}