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<iostream>
#include<algorithm>
#include<cstring>
#include<stdio.h>
#define MAX 200005
using namespace std;
int tree1[MAX * 4], insert[MAX];
int tree2[MAX * 4];
void update(int k)
{
tree1[k] = max(tree1[2 * k], tree1[2 * k + 1]);
tree2[k] = min(tree2[2 * k], tree2[2 * k + 1]);
}
void build(int k, int left, int right)// 建树
{
if (left == right)
{
tree1[k] = insert[left];
tree2[k] = insert[left];
return;
}
int n = (left + right) / 2;
build(2 * k, left, n);
build(2 * k + 1, n + 1, right);
update(k);
}
int query_max(int k, int left, int right, int query_left, int query_right)//查询区间
{
if (query_left > right || query_right < left)
return 0;
if (query_left <= left && query_right >= right)
return tree1[k];
int n = (left + right) / 2;
int res1 = query_max(2 * k, left, n, query_left, query_right);
int res2 = query_max(2 * k + 1, n + 1, right, query_left, query_right);
return max(res1, res2);
}
int query_min(int k, int left, int right, int query_left, int query_right)//查询区间
{
if (query_left > right || query_right < left)
return 0x3f3f3f;
if (query_left <= left && query_right >= right)
return tree2[k];
int n = (left + right) / 2;
int res1 = query_min(2 * k, left, n, query_left, query_right);
int res2 = query_min(2 * k + 1, n + 1, right, query_left, query_right);
return min(res1, res2);
}
int main()
{
int n, m;
while (~scanf("%d%d", &n, &m))
{
for (int i = 1; i <= n; i++)
scanf("%d", &insert[i]);
build(1, 1, n);
while (m--)
{
int l, r;
scanf("%d%d", &l, &r);
int ans = query_max(1, 1, n, l, r) - query_min(1, 1, n, l, r);
printf("%d\n", ans);
}
}
return 0;
}