Poj 3264 balanced lineup

Source: Internet
Author: User

The question is: a farmer has a nheaded ox, and the height of each ox is different, so that you can find out the height difference between the highest ox and the lowest ox in the specified range.

Solution:

When I saw the question, I thought of the Line Segment tree. Then I used the recursive line segment tree. At the beginning, I had to replace it with a non-recursive version. Then I optimized the input and output for, this made me feel the beauty of optimization !!!

 1 #include<iostream> 2 #include<string> 3 #include<algorithm> 4 #define maxn 50100 5  6 using namespace std; 7  8 int MAX[maxn<<2], MIN[maxn<<2]; 9 int a[maxn];10 11 void PushUp(int rt)12 {13     MAX[rt]=max(MAX[rt<<1],MAX[rt<<1|1]);14     MIN[rt]=min(MIN[rt<<1],MIN[rt<<1|1]);15 }16 17 void Build(int l,int r,int rt)18 {19     if(l==r)20     {21         MAX[rt]=a[l];22         MIN[rt]=a[l];23     }24     else25     {26         int m=(l+r)>>1;27         Build(l,m,rt<<1);28         Build(m+1,r,rt<<1|1);29         PushUp(rt);30     }31 }32 33 void Query(int L,int R,int l,int r,int rt, int &mx, int &mn)34 {35     if(L<=l&&r<=R)36     {37         mx = max(MAX[rt], mx);38         mn = min(MIN[rt], mn);39         return;40     }41     int m=(r+l)>>1;42     if(L<=m)43         Query(L,R,l,m,rt<<1,mx,mn);44     if(R>m)45         Query(L,R,m+1,r,rt<<1|1,mx,mn);46 }47 48 49 int main()50 {51     int n, q;52     scanf("%d%d", &n, &q);53     for(int i=1; i<=n; ++i)54         scanf("%d",&a[i]);55     Build(1,n,1);56     int c, d, mx, mn;57     for(int i=0; i<q; ++i)58     {59         mx = 0, mn = 10000000;60         scanf("%d %d", &c, &d);61         Query(c,d,1,n,1, mx, mn);62         printf("%d\n", mx-mn); 63     }64     return 0;65 }

For non-recursive versions, see this article: 48299459.

Poj 3264 balanced lineup

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.