Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 41162 | Accepted: 19327 | |
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
Output
Sample Input
6 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0
Source
/* * @Author: LinK * @Date: 2015-10-31 18:20:11 * @Last Modified by: LinK * @Last Modified time: 2015-10-31 18:27:30 */ #include <map> #include <set> #include <cmath> #include <stack> #include <queue> #include <vector> #include <cstdio> #include <string> #include <utility> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; #define eps 1e-8 #define randin srand((unsigned int)time(NULL)) #define input freopen("input.txt","r",stdin) #define debug(s) cout << "s = " << s << endl; #define outstars cout << "*************" << endl; const double PI = acos(-1.0); const int inf = 0x3f3f3f3f; const int INF = 0x7fffffff; typedef long long ll; const int maxn = 50010; struct Node { int ma, mi; } tree[maxn << 2]; int num[maxn]; int n, q; void build(int rt, int l, int r) { if (l == r) { tree[rt].ma = num[l]; tree[rt].mi = num[l]; return; } int mid = (l + r) >> 1; build(rt << 1, l, mid); build(rt << 1 | 1, mid + 1, r); tree[rt].ma = max(tree[rt << 1].ma, tree[rt << 1 | 1].ma); tree[rt].mi = min(tree[rt << 1].mi, tree[rt << 1 | 1].mi); } int query_ma(int rt, int l, int r, int L, int R) { if (L <= l && R >= r) return tree[rt].ma; int mid = (l + r) >> 1; if (R <= mid) return query_ma(rt << 1, l, mid, L, R); if (L > mid) return query_ma(rt << 1 | 1, mid + 1, r, L, R); return max(query_ma(rt << 1, l, mid, L, R), query_ma(rt << 1 | 1, mid + 1, r, L, R)); } int query_mi(int rt, int l, int r, int L, int R) { if (L <= l && R >= r) return tree[rt].mi; int mid = (l + r) >> 1; if (R <= mid) return query_mi(rt << 1, l, mid, L, R); if (L > mid) return query_mi(rt << 1 | 1, mid + 1, r, L, R); return min(query_mi(rt << 1, l, mid, L, R), query_mi(rt << 1 | 1, mid + 1, r, L, R)); } int main() { while (~scanf("%d %d", &n, &q)) { for (int i = 1; i <= n; i ++) scanf("%d", &num[i]); build(1, 1, n); int a, b; while (q --) { scanf("%d %d", &a, &b); int ma = query_ma(1, 1, n, a, b); int mi = query_mi(1, 1, n, a, b); printf("%d\n", ma - mi); } } return 0; }
原文:http://www.cnblogs.com/LinKArftc/p/4925951.html