Poj 3264 balanced lineup

Source: Internet
Author: User

Question link: http://poj.org/problem? Id = 3264


It is to give you a string of numbers and ask you the difference between the maximum number and the minimum number .......


Train of Thought: the most basic line segment tree only needs to build and query, and the modification is saved, but the query needs to write two. One query has the maximum value and the other one has the minimum value ...... Then the AC can be dropped ..... However, poj classifies it into rmq ....


Code:

# Include <cstdio> # include <cmath> # include <algorithm> # include <iostream> # define Max 50010 using namespace STD; struct node {int L, R; int Minn, maxx;} node [Max * 4]; int num [Max]; void buildtree (int I, int L, int R) {node [I]. L = L; node [I]. R = r; If (L = r) {node [I]. maxx = node [I]. minn = num [l]; return;} int mid = (L + r)/2; buildtree (I * 2, L, mid); buildtree (I * 2 + 1, mid + 1, R); node [I]. maxx = max (node [I * 2]. maxx, node [I * 2 + 1]. maxx); node [I]. minn = min (node [I * 2]. minn, node [I * 2 + 1]. minn);} int query (int I, int L, int R) // query the maximum value {If (node [I]. L = L & node [I]. R = r) {return node [I]. maxx;} int mid = (node [I]. L + node [I]. r)/2; If (r <= mid) return query (I * 2, L, R); else if (L> mid) return query (I * 2 + 1, l, R); else {return max (query (I * 2, L, mid), query (I * 2 + 1, Mid + 1, R ));}} int query1 (int I, int L, int R) // query the minimum value {If (node [I]. L = L & node [I]. R = r) {return node [I]. minn;} int mid = (node [I]. L + node [I]. r)/2; If (r <= mid) return query1 (I * 2, L, R); else if (L> mid) return query1 (I * 2 + 1, l, R); else {return (min (query1 (I * 2, L, mid), query1 (I * 2 + 1, Mid + 1, r) ;}} int main () {int N, Q; while (scanf ("% d", & N, & Q) = 2) {int I; for (I = 1; I <= N; I ++) {scanf ("% d", & num [I]) ;}buildtree (1, 1, n); for (I = 1; I <= Q; I ++) {int A, B; scanf ("% d", & A, & B ); int M1 = query (1, a, B); int m2 = query1 (1, a, B); printf ("% d \ n", M1-M2 );}} 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.