Http://poj.org/problem? Id = 3264
Question: Enter n numbers and m queries. For each query, enter l, r to find the difference between the maximum number and the minimum number in the range [l, r.
Ideas:
When I used a line segment tree, the node added two fields to record the maximum and minimum values of the interval. Then, set the global variables maxh and minh to the maximum and minimum values in the dynamic maintenance interval [l, r.
However, the line segment tree does not take a long time, such as 3 s +...
# Include
# Include
# Include using namespace std; const int INF = 0x3f3f3f3f; const int maxn = 50005; struct line {int l; int r; int minh; int maxh ;} tree [maxn <2]; int a [maxn]; int maxh; int minh; void build (int v, int l, int r) {tree [v]. l = l; tree [v]. r = r; if (l = r) {tree [v]. maxh = a [l]; tree [v]. minh = a [l]; return;} int mid = (l + r)> 1; build (v * 2, l, mid ); build (v * 2 + 1, mid + 1, r); tree [v]. maxh = max (tree [v * 2]. maxh, tree [v * 2 + 1]. maxh); tree [v]. minh = min (tree [v * 2]. minh, tree [v * 2 + 1]. minh);} void query (int v, int l, int r) {if (tree [v]. l = l & tree [v]. r = r) {maxh = max (maxh, tree [v]. maxh); // maxh, minh Dynamic Maintenance minh = min (minh, tree [v]. minh); return;} int mid = (tree [v]. l + tree [v]. r)> 1; if (r <= mid) query (v * 2, l, r); else {if (l> mid) query (v * 2 + 1, l, r); else {query (v * 2, l, mid); query (v * 2 + 1, mid + 1, r) ;}} int main () {int n, m; scanf ("% d", & n, & m); for (int I = 1; I <= n; I ++) scanf ("% d", & a [I]); build (1, 1, n); int l, r; while (m --) {scanf ("% d", & l, & r); maxh = 0; minh = INF; // do not forget to initialize query (1, l, r ); printf ("% d \ n", maxh-minh);} return 0 ;}