Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 47073 | Accepted: 22092 | |
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
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
Sample Input
6 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0
题意:给出n个数,q组询问,查询区间[l, r]中最大值与最小值的差。
RMQ裸题,感觉不能更裸。
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <iostream>
#include <assert.h>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int M = 1e6 + 10;
int a[M];
int rmq[M][30];
int rmq2[M][30];
int Log[M + 5];
void rmqinit(int n)
{
Log[0] = Log[1]= 0;
for (int i = 2; i <= M; i++)
Log[i] = Log[i >> 1] + 1;
for (int i = 1; i <= n; i++) {
rmq[i][0] = a[i];
rmq2[i][0] = a[i];
}
for (int j = 1; j <= Log[n]; j++) {
int k = 1 << (j - 1);
for (int i = 1; i + (1 << j) - 1 <= n; i++) {
rmq[i][j] = min(rmq[i][j - 1], rmq[i + k][j - 1]);
rmq2[i][j] = max(rmq2[i][j - 1], rmq2[i + k][j - 1]);
}
}
}
int rmquery(int a, int b) //查最小值
{
if (a > b) return 0;
int t = Log[b - a + 1];
//int t = log((double)(b-a+1)) / log(2.0);
return min(rmq[a][t], rmq[b-(1<<t)+1][t]);
}
int rmquery2(int a, int b) //查最大值
{
if (a > b) return 0;
int t = Log[b - a + 1];
//int t = log((double)(b-a+1)) / log(2.0);
return max(rmq2[a][t], rmq2[b-(1<<t)+1][t]);
}
int main()
{
int n, q;
while (cin >> n >> q) {
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
rmqinit(n);
int le, ri;
while (q--) {
scanf("%d%d", &le, &ri);
int ans = rmquery2(le, ri) - rmquery(le, ri);
printf("%d\n", ans);
}
}
return 0;
}