Poj 3264 Balanced Lineup RMQ line segment tree implementation
Balanced Lineup
Time Limit:5000 MS |
|
Memory Limit:65536 K |
Total Submissions:36613 |
|
Accepted:17141 |
Case Time Limit:2000 MS |
Description
For the daily milking, Farmer John'sNCows (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 shocould not differ too much in height.
Farmer John has made a listQ(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,
NAnd
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
AAnd
B(1 ≤
A≤
B≤
N), Representing the range of cows from
ATo
BIntrusive.
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 31734251 54 62 2
Sample Output
630
For RMQ, it is best to use the ST algorithm to implement RMQ, which may be highly efficient .. I used a line segment tree. It took 1500 ms... (Cover
Maybe it's the scum I wrote. If you have time to learn the st algorithm, after all, whether or not you can use a line segment tree or not depends on your character. Maybe my code is too scum, but there are still some optimizations that can be optimized, but they are not optimized. That's it. The code is easy to understand.
# Include
# Include
# Define MAX 501000 struct tree {int t, s;} st [MAX * 4]; int tall = INT_MIN, shor = INT_MAX; int max (int a, int B) {return a> B? A: B;} int min (int a, int B) {return a> B? B: a;} void build (int left, int right, int pos) {if (left = right) {scanf (% d, & st [pos]. t); st [pos]. s = st [pos]. t; return;} int mid = (left + right)> 1; build (left, mid, pos <1); build (mid + 1, right, pos <1 | 1); st [pos]. t = max (st [pos <1]. t, st [pos <1 | 1]. t); st [pos]. s = min (st [pos <1]. s, st [pos <1 | 1]. s);} // L, R, void query (int L, int R, int x, int y, int pos) {if (L = x & R = y) {tall = max (tall, st [pos]. t); shor = min (shor, st [pos]. s); return;} int mid = (L + R)> 1; if (mid <x) {www. bkjia. comquery (mid + 1, R, x, y, pos <1 | 1);} else if (mid> = y) {query (L, mid, x, y, pos <1);} else {query (L, mid, x, mid, pos <1); query (mid + 1, R, mid + 1, y, pos <1 | 1) ;}} int main () {int n, q; scanf (% d, & n, & q); build (1, n, 1); for (int I = 0; I <q; ++ I) {int a, B; scanf (% d, & a, & B ); tall = INT_MIN, shor = INT_MAX; query (1, n, a, B, 1); printf (% d, tall-shor);} return 0 ;}