BZOJ1636: [Usaco2007 Jan]Balanced Lineup

1636: [Usaco2007 Jan]Balanced Lineup

Time Limit: 5 Sec  Memory Limit: 64 MB
Submit: 476  Solved: 345
[Submit][Status]

Description

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.

Input

* 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 <= A <= B <= N), representing the range of cows from A to B inclusive.

Output

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

Sample Input

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

Sample Output

6
3
0

HINT

 

Source

题解:
裸RMQ,英语渣哭了QAQ....
代码:
 #include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<iostream>
#define maxn 50000+100
#define maxm 100000
using namespace std;
int n,m,a[maxn],f[maxn][],g[maxn][];
inline int read()
{
int x=,f=;char ch=getchar();
while(ch<''||ch>''){if(ch=='-')f=-;ch=getchar();}
while(ch>=''&&ch<=''){x=x*+ch-'';ch=getchar();}
return x*f;
}
void rmq()
{
for(int i=;i<=n;i++)f[i][]=a[i];
for(int i=;i<=floor(log(n)/log());i++)
for(int j=;j<=n-(<<i)+;j++)
f[j][i]=max(f[j][i-],f[j+(<<(i-))][i-]);
for(int i=;i<=n;i++)g[i][]=a[i];
for(int i=;i<=floor(log(n)/log());i++)
for(int j=;j<=n-(<<i)+;j++)
g[j][i]=min(g[j][i-],g[j+(<<(i-))][i-]);
}
int query(int x,int y)
{
int z=floor(log(y-x+)/log());
return max(f[x][z],f[y-(<<z)+][z])-min(g[x][z],g[y-(<<z)+][z]);
}
int main()
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
n=read();m=read();
for(int i=;i<=n;i++)a[i]=read();
rmq();
while(m--)
{
int x=read(),y=read();
printf("%d\n",query(x,y));
}
return ;
}
上一篇:linux入门之用户管理


下一篇:Nancy启用跨站攻击防护(CSRF)