首页 > 专题系列 > Java解POJ > POJ 3264 Balanced Lineup [解题报告] Java
2013
11-12

POJ 3264 Balanced Lineup [解题报告] Java

Balanced Lineup

问题描述 :

For the daily milking, Farmer John’s N cows (1 ≤ N ≤ 50,000) always line up in the same order. One day Farmer John decides to organize a game of Ultimate Frisbee with some of the cows. To keep things simple, he will take a contiguous range of cows from the milking lineup to play the game. However, for all the cows to have fun they should not differ too much in height.

Farmer John has made a list of Q (1 ≤ Q ≤ 200,000) potential groups of cows and their heights (1 ≤ height ≤ 1,000,000). For each group, he wants your help to determine the difference in height between the shortest and the tallest cow in the group.

输入:

Line 1: Two space-separated integers, N and Q.

Lines 2..N+1: Line i+1 contains a single integer that is the height of cow i

Lines N+2..N+Q+1: Two integers A and B (1 ≤ ABN), representing the range of cows from A to B inclusive.

输出:

Lines 1..Q: Each line contains a single integer that is a response to a reply and indicates the difference in height between the tallest and shortest cow in the range.

样例输入:

6 3
1
7
3
4
2
5
1 5
4 6
2 2

样例输出:

6
3
0

解题代码:

//* @author: 82638882@163.com
import java.io.*;
public class Main
{
 static int[][] q=new int[160001][17];
 static int[][] p=new int[160001][17];
 public static void main(String[] args) throws NumberFormatException, IOException
 {
	InputStreamReader is=new InputStreamReader(System.in);
	BufferedReader in=new BufferedReader(is);
	String[] ss=in.readLine().split(" ");
	int n=Integer.parseInt(ss[0]);
	int k=Integer.parseInt(ss[1]);
	int v=(int)(Math.log(n)/Math.log(2));
	for(int i=1;i<=n;i++)
		q[i][0]=p[i][0]=Integer.parseInt(in.readLine());
	for(int j=1;j<=v;j++)
	{
		for(int i=1;i<=n;i++)
		{
		 int u= (int)Math.pow(2, j-1)+i;
		 q[i][j]=Math.max(q[i][j-1],q[u][j-1]);
		 p[i][j]=Math.min(p[i][j-1],p[u][j-1]);
		}
	}
      while((k--)!=0)
      {
	ss=in.readLine().split(" ");
	int x1=Integer.parseInt(ss[0]);
	int x2=Integer.parseInt(ss[1]);
	int t=x2-x1;
	if(t!=0) t=(int)(Math.log(t)/Math.log(2));
	int o=(int)Math.pow(2, t);
	int max=Math.max(q[x1][t], q[x2-o+1][t]);
	int min=Math.min(p[x1][t], p[x2-o+1][t]);
	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。此时的数据量还是很小的,耗时却不短。这种方法确实可以,当然或许还有其他的优化方案,但是优化只能针对某些数据,不太可能在所有情况下都能在可接受的时间内求解出答案。

  2. 题本身没错,但是HDOJ放题目的时候,前面有个题目解释了什么是XXX定律。
    这里直接放了这个题目,肯定没几个人明白是干啥

  3. 第二块代码if(it != mp.end())应改为if(it != mp.end() && (i+1)!=(it->second +1));因为第二种解法如果数组有重复元素 就不正确