2013
11-12

# 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: [email protected]/* <![CDATA[ */!function(t,e,r,n,c,a,p){try{t=document.currentScript||function(){for(t=document.getElementsByTagName('script'),e=t.length;e--;)if(t[e].getAttribute('data-cfhash'))return t[e]}();if(t&&(c=t.previousSibling)){p=t.parentNode;if(a=c.getAttribute('data-cfemail')){for(e='',r='0x'+a.substr(0,2)|0,n=2;a.length-n;n+=2)e+='%'+('0'+('0x'+a.substr(n,2)^r).toString(16)).slice(-2);p.replaceChild(document.createTextNode(decodeURIComponent(e)),c)}p.removeChild(t)}}catch(u){}}()/* ]]> */
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
{
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++)
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)
{
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))；因为第二种解法如果数组有重复元素 就不正确