Cornfields
Time Limit: 1000MS |
|
Memory Limit: 30000K |
Total Submissions: 4034 |
|
Accepted: 1933 |
Description
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
Source
USACO 2003 March Green
第一行有三个参数N、B、K。
题意为,在一个N*N的矩阵中,进行K次搜索,每次搜索对于给定的X、Y为左上角,
搜索B*B的矩阵范围,求这个范围内最大值和最小值之差,输出。
应该是RMQ的题目,用暴力水过- -。
注意点:
1、不能使用多case,即while(scanf("%d%d%d", &N, &B, &K) != EOF),导致TLE。(- -!!)
2、统一输入和搜索时候的坐标统一性。
代码(1AC 1TLE):
#include <cstdio>
#include <cstdlib>
int field[300][300];
int N, B, K;
int main(void){
int X, Y;
int i, j;
int min, max, tmp;
scanf("%d%d%d", &N, &B, &K);
for (i = 1; i <= N; i++){
for (j = 1; j <= N; j++){
scanf("%d", &field[i][j]);
}
}
while (K --){
scanf("%d%d", &X, &Y);
min = max = field[X][Y];
for (i = X; i < X + B; i++){
for (j = Y; j < Y + B; j++){
if (min > field[i][j]){
min = field[i][j];
}
if (max < field[i][j]){
max = field[i][j];
}
//printf("%d ", field[i][j]);
}
//printf("\n");
}
printf("%d\n", max - min);
}
return 0;
}