C - RMQ Time Limit:5000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u Submit Status Practice POJ 3264
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
//@auther Yang Zongjun
//http://www.cnblogs.com/wuyiqi/archive/2011/10/24/2223017.html
//http://blog.csdn.net/acdreamers/article/details/8692384
///注意啊,雨神給的PPT上關于rmq_find()函數有誤,
///以後就用這個模闆了, 是我敲代碼時看錯了PPT是對的
#include <iostream>
#include <cstdio>
#include <cmath>
//#include <string.h>
//#include <string>
#include <cstring>
using namespace std;
#define PI acos(-1.0)
#define EPS 1e-8
const int MAXN = 50005;
const int INF = 2100000000;
int a[MAXN], ans[MAXN];
int dpmin[MAXN][20], dpmax[MAXN][20];
int n, q;
void rmq_st()
{
//memset(dpmax, 0, sizeof(dpmax));
//memset(dpmin, 0, sizeof(dpmin));
for(int i = 0; i < n; i++)
{
dpmin[i][0] = a[i];
dpmax[i][0] = a[i];
}
int m = (int)(log(1.0 * n) / log(2.0));
for(int j = 1; j <= m; j++)
{
int t = n - (1 << j) + 1;
for(int i = 0; i <= t; i++)
{
dpmin[i][j] = min(dpmin[i][j - 1], dpmin[i + (1 << (j - 1))][j - 1]);
dpmax[i][j] = max(dpmax[i][j - 1], dpmax[i + (1 << (j - 1))][j - 1]);
}
}
}
inline int rmq_findmin(int l, int r)
{
int k = (int)(log(1.0 * (r - l +1)) / log(2.0));
return min(dpmin[l][k], dpmin[r - (1 << k) + 1][k]);
}
inline int rmq_findmax(int l, int r)
{
int k = (int)(log(1.0 * (r - l +1)) / log(2.0));
return max(dpmax[l][k], dpmax[r - (1 << k) + 1][k]);
}
int main()
{
//freopen("C:/Users/Admin/Desktop/input.txt", "r", stdin);
while(~scanf("%d %d", &n, &q))
{
int x, y;
for(int i = 0; i < n; i++)
{
//cin >> a[i];
scanf("%d", &a[i]);
}
rmq_st();
for(int i = 0; i < q; i++)
{
//cin >> x >> y;
// cout << rmq_findmax(x-1,y-1) - rmq_findmin(x-1,y-1) << endl;
scanf("%d%d", &x, &y);
printf("%d\n", rmq_findmax(x-1,y-1) - rmq_findmin(x-1, y-1));
}
}
return 0;
}