码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 3264 Balanced Lineup

时间:2018-10-27 11:58:44      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:输入   details   ace   uil   http   efi   algo   线段   tps   

题目大意是:一个农夫有N头牛,每头牛的高度不同,让你找出指定区间最高牛和最低牛的高度差。

解题思路:

一看到题目就想到了线段树,然后用了递归的线段树,一开始一直TLE,本来想换成非递归版本,后来输入输出优化了一下就A了,这让我感受到了优化的妙处!!!

 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     else
25     {
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 }

非递归版可以去看看这篇文章了解下:https://blog.csdn.net/zearot/article/details/48299459

POJ 3264 Balanced Lineup

标签:输入   details   ace   uil   http   efi   algo   线段   tps   

原文地址:https://www.cnblogs.com/kerman/p/9860412.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!