Balanced Lineup
Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 47087   Accepted: 22101
Case Time Limit: 2000MS

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

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 Input

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

Sample Output

6
3
0
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
const int MAXN=;
int n,m;
int maxm[MAXN][],minm[MAXN][];
void init_st(int size)
{
for(int j=;j<;j++)
{
for(int i=;i<=n;i++)
{
if(i+(<<j)-<=n)
{
maxm[i][j]=max(maxm[i][j-],maxm[i+(<<(j-))][j-]);
minm[i][j]=min(minm[i][j-],minm[i+(<<(j-))][j-]);
}
}
}
}
int rmq_st(int l,int r)
{
int limit=(int)(log(0.0+(r-l+))/log(2.0));
int mn=min(minm[l][limit],minm[r-(<<limit)+][limit]);
int mx=max(maxm[l][limit],maxm[r-(<<limit)+][limit]);
return mx-mn;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=;i<=n;i++)
{
scanf("%d",&maxm[i][]);
minm[i][]=maxm[i][];
}
init_st(n);
for(int i=;i<m;i++)
{
int l,r;
scanf("%d%d",&l,&r);
int res=rmq_st(l,r);
printf("%d\n",res);
}
}
return ;
}

最新文章

  1. ASP.NET Core 中文文档 第四章 MVC(2.2)模型验证
  2. seajs模块化作用理解(一句话)
  3. 从零开始搭建Docker Swarm集群
  4. Hadoop2.6.0在Ubuntu Kylin14.04上的配置
  5. [Leetcode][001] Two Sum (Java)
  6. Android Studio 设置LogCat 颜色
  7. Spring AOP 本质(4)
  8. XML解析之DOM解析技术案例
  9. LaTeX排版指南
  10. Spring第二篇【Core模块之快速入门、bean创建细节、创建对象】
  11. oracle 常用知识积累
  12. 敏捷冲刺每日报告五(Java-Team)
  13. weakref 待解决.
  14. 开源)嗨,Java,你可以生成金山词霸的二维码分享海报吗?
  15. Vue 折叠面板Collapse在标题上添加组件后,阻止面板冒泡的用法
  16. LostRoutes项目日志——敌人精灵Enemy解析
  17. can协议
  18. Java自学之路(小白向)
  19. Jenkins配置自动打包 -- 遇到的坑
  20. resume.c

热门文章

  1. iOS_mapKit与Core Location
  2. python装饰器实现HTTP请求耗时和入参返回日志记录
  3. Elasticsearch6.4.3安装
  4. 互联网高并发之Hystrix实现服务隔离和降级
  5. mongodb,redis简单学习
  6. uvalive 6938 区间dp
  7. SPOJ1825 FTOUR2 - Free tour II
  8. Spring Boot入门——freemarker
  9. java:OutputStream和InputStream 输出输入流,FileOutputStream,FileInputStream写入读取流
  10. 2017-03-05 CentOS中结合Nginx部署dotnet core Web应用程序