题目要我们求一个块内的最值,可以把块分成多行,每行求一次RMQ即可,因此也要对每一行建一个ST表。
#include <algorithm>
#include <cmath>
#include <cstdio>
#define fre(f) freopen(f ".in", "r", stdin), freopen(f ".out", "w", stdout)
#define inf 0x3f3f3f3f
const int N = 255;
using namespace std;
int n, b, q, lb;
int stmax[N][N][10], stmin[N][N][10], h[N][N];
void init()
{
lb = log2(b);
for (int i = 1; i < 10; i++)
{
int len = pow(2, i - 1);
if (len * 2 > n) break;
for (int j = 1; j <= n; j++)
for (int k = n - len * 2 + 1; k >= 1; k--)
{
stmax[j][k][i] = max(stmax[j][k][i - 1], stmax[j][k + len][i - 1]);
stmin[j][k][i] = min(stmin[j][k][i - 1], stmin[j][k + len][i - 1]);
}
}
}
int rmq(int x, int y)
{
int ma = 0, mi = inf;
for (int i = x + b - 1; i >= x; i--)
{
ma = max(ma, max(stmax[i][y][lb], stmax[i][y + b - (1 << lb)][lb]));
mi = min(mi, min(stmin[i][y][lb], stmin[i][y + b - (1 << lb)][lb]));
}
return ma - mi;
}
int main()
{
scanf("%d%d%d", &n, &b, &q);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
{
scanf("%d", &h[i][j]);
stmax[i][j][0] = stmin[i][j][0] = h[i][j];
}
init();
while (q--)
{
int x, y;
scanf("%d%d", &x, &y);
printf("%d\n", rmq(x, y));
}
return 0;
}