POJ-2019 Cornfields(二维RMQ)

Posted pixel-teee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ-2019 Cornfields(二维RMQ)相关的知识,希望对你有一定的参考价值。

分析:(f[i][j][k])表示(i到2^k)行和(j到2^k)列的矩阵中的最大值,可以从四个部分状态转移过来,(f[i][j][k - 1], f[i + (1 << (k - 1))][j][k - 1]), f[i][j + (1 << (k - 1))][k - 1], f[i + (1 << (k - 1))][j + (1 << (k - 1))][k - 1])

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>

using namespace std;
const int N = 300;
const int M = 10;
int f1[N][N][M], f2[N][N][M];
int n, b, q;
int k;

void init()
{
	for(int k = 1; k <= 8; ++k)
		for(int i = 1; i + (1 << k) - 1 <= n; ++i)
			for (int j = 1; j + (1 << k) - 1 <= n; ++j)
			{
				f1[i][j][k] = max(max(f1[i][j][k - 1], f1[i + (1 << (k - 1))][j][k - 1]), max(f1[i][j + (1 << (k - 1))][k - 1], f1[i + (1 << (k - 1))][j + (1 << (k - 1))][k - 1]));
				f2[i][j][k] = min(min(f2[i][j][k - 1], f2[i + (1 << (k - 1))][j][k - 1]), min(f2[i][j + (1 << (k - 1))][k - 1], f2[i + (1 << (k - 1))][j + (1 << (k - 1))][k - 1]));
			}
}

int query1(int x1, int y1, int x2, int y2)
{
	int a = f1[x1][y1][k], b = f1[x2 - (1 << k) + 1][y1][k], c = f1[x1][y2 - (1 << k) + 1][k], d = f1[x2 - (1 << k) + 1][y2 - (1 << k) + 1][k];
	return max(max(a, b), max(c, d));
}

int query2(int x1, int y1, int x2, int y2)
{
	int a = f2[x1][y1][k], b = f2[x2 - (1 << k) + 1][y1][k], c = f2[x1][y2 - (1 << k) + 1][k], d = f2[x2 - (1 << k) + 1][y2 - (1 << k) + 1][k];
	return min(min(a, b), min(c, d));
}

int main()
{	
	scanf("%d%d%d", &n, &b, &q);

	int c;
	for(int i = 1; i <= n; ++i)
		for (int j = 1; j <= n; ++j)
		{
			scanf("%d", &c);
			f1[i][j][0] = f2[i][j][0] = c;
		}

	k = log((double)b) / log((double)2);
	init();

	int x1, y1;
	while (q--)
	{
		scanf("%d%d", &x1, &y1);
		int x2 = x1 + b - 1, y2 = y1 + b - 1;
		int e1 = query1(x1, y1, x2, y2);
		int e2 = query2(x1, y1, x2, y2);
		printf("%d
", e1 - e2);
	}
	
	return 0;
}

以上是关于POJ-2019 Cornfields(二维RMQ)的主要内容,如果未能解决你的问题,请参考以下文章

POJ2019 Cornfields

POJ 2019 Cornfields 二维线段树的初始化与最值查询

poj2019(二维RMQ)

poj 2019 Cornfields

Cornfields(poj2019)

POJ2019:二维ST算法解决静态方阵最值问题