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.
思路:题意是给你n个点,每次找出某个区间中最大数与最小数的差。范围较大,所以要用到线段树来求解,比较裸的模板题。
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; typedef long long ll; #define lson l, mid, rt << 1 #define rson mid + 1, r, rt << 1 | 1 const int maxn = 5e4 + 10; const int inf = 0x3f3f3f3f; int Max[maxn * 4], Min[maxn * 4]; void push_up(int rt) { Max[rt] = max(Max[rt << 1], Max[rt << 1 | 1]); Min[rt] = min(Min[rt << 1], Min[rt << 1 | 1]); } void build(int l, int r, int rt) { if(l == r) { scanf("%d", &Max[rt]); Min[rt] = Max[rt]; return; } int mid = (l + r) >> 1; build(lson); build(rson); push_up(rt); } int query_max(int L, int R, int l, int r, int rt) { if(L <= l && r <= R) { return Max[rt]; } int mid = (l + r) >> 1; int res = -1; if(L <= mid) res = max(res, query_max(L, R, lson)); if(R > mid) res = max(res, query_max(L, R, rson)); return res; } int query_min(int L, int R, int l, int r, int rt) { if(L <= l && r <= R) { return Min[rt]; } int mid = (l + r) >> 1; int res = inf; if(L <= mid) res = min(res, query_min(L, R, lson)); if(R > mid) res = min(res, query_min(L, R, rson)); return res; } int main() { int n, q; scanf("%d%d", &n, &q); build(1, n, 1); while(q--) { int x, y; scanf("%d%d", &x, &y); int ans = query_max(x, y, 1, n, 1) - query_min(x, y, 1, n, 1); printf("%d\n", ans); } return 0; }