Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 36820 | Accepted: 17244 | |
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
#include <cstdio> #include <cstring> #include <algorithm> #define lson l, mid, rt << 1 #define rson mid + 1, r, rt << 1 | 1 using namespace std; int const INF = 0x3fffffff; int const MAX = 50005; int a[MAX], ma, mi; struct node { int l, r; int mi, ma; int mid() { return (l + r) / 2; } }t[3 * MAX]; void push_up(int rt) { t[rt].ma = max(t[rt << 1].ma, t[rt << 1 | 1].ma); t[rt].mi = min(t[rt << 1].mi, t[rt << 1 | 1].mi); } void Build(int l, int r, int rt) { t[rt].l = l; t[rt].r = r; if(l == r) { t[rt].ma = t[rt].mi = a[l]; return; } else { int mid = t[rt].mid(); Build(lson); Build(rson); push_up(rt); } } void Query(int l, int r, int rt) { if(t[rt].l == l && t[rt].r == r) { ma = max(t[rt].ma, ma); mi = min(t[rt].mi, mi); return; } else { int mid = t[rt].mid(); if(r <= mid) Query(l, r, rt << 1); else if(l > mid) Query(l, r, rt << 1 | 1); else { Query(lson); Query(rson); } } } int main() { int n, m; scanf("%d %d", &n, &m); for(int i = 1; i <= n; i++) scanf("%d", &a[i]); Build(1, n, 1); for(int i = 1; i <= m; i++) { int l, r; scanf("%d %d", &l, &r); ma = -INF; mi = INF; Query(l, r, 1); printf("%d\n", ma - mi); } }
POJ 3264 Balanced Lineup (线段树单点更新 区间查询)
原文地址:http://blog.csdn.net/tc_to_top/article/details/43931185