Poj 3264 Balanced Lineup (RMQ line segment tree)

Source: Internet
Author: User

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 ;}
  
 





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.