首页 > 专题系列 > Java解POJ > POJ 2019 Cornfields [解题报告] Java
2013
11-10

POJ 2019 Cornfields [解题报告] Java

Cornfields

问题描述 :

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.

输入:

* 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.

输出:

* Lines 1..K: A single integer per line representing the difference between the max and the min in each query.

样例输入:

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

样例输出:

5

解题代码:

//* @author: [email protected]
import java.io.*;
import java.util.Arrays;
public class Main
{
	
 public static void main(String[] args) throws IOException
 {
  InputStreamReader is=new InputStreamReader(System.in);
  BufferedReader in=new BufferedReader(is);
  String[] ss=in.readLine().split(" ");
  int a=Integer.parseInt(ss[0]);
  int b=Integer.parseInt(ss[1]);
  int c=Integer.parseInt(ss[2]);
  int[][] p=new int[a][a];
  for(int i=0;i< a;i++)
  {
   ss=in.readLine().split(" ");
   for(int j=0;j< a;j++)
     p[i][j]=Integer.parseInt(ss[j]);
  }
  while((c--)!=0)
  {
   ss=in.readLine().split(" ");
   int x=Integer.parseInt(ss[0]);
   int y=Integer.parseInt(ss[1]);
   int max=-99999,min=99999;
   for(int i=x-1;i< x+b-1;i++)
   {
     for(int j=y-1;j< y+b-1;j++)
     {
	if(p[i][j]>max)max=p[i][j];
	  if(p[i][j]< min) min=p[i][j];
	}
      }
      System.out.println(max-min);
    }
  }
}

  1. 给你一组数据吧:29 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 1000。此时的数据量还是很小的,耗时却不短。这种方法确实可以,当然或许还有其他的优化方案,但是优化只能针对某些数据,不太可能在所有情况下都能在可接受的时间内求解出答案。