(区间最值差)C - Balanced Lineup POJ - 3264

区间最值差,线段树维护一个最大值,一个最小值。查询时,max-min就是结果

 1 #include <iostream>
 2 #include <cstring>
 3 #include <vector>
 4 #include <algorithm>
 5 #define lson l,m,rt<<1
 6 #define rson m+1,r,rt<<1|1
 7 #define mem(x) memset(x,0,sizeof(x))
 8 using namespace std;
 9 const int INF=9999999;
10 const int maxn=50000+5;
11 int Mi[maxn<<4];
12 int Ma[maxn<<4];
13 void pushup(int rt){
14     Mi[rt]=min(Mi[rt<<1],Mi[rt<<1|1]);
15     Ma[rt]=max(Ma[rt<<1],Ma[rt<<1|1]);
16 }
17 void build(int l,int r,int rt){
18     if(l==r){
19         scanf("%d",&Mi[rt]);
20         Ma[rt]=Mi[rt];
21         return;
22     }
23     int m=(l+r)>>1;
24     build(lson);
25     build(rson);
26     pushup(rt);
27 }
28 
29 pair <int,int> query(int L,int R,int l,int r,int rt){
30     if(L<=l&&R>=r)
31     {
32         pair <int,int>p(Mi[rt],Ma[rt]);
33         //cout <<Mi[rt]<<" "<<Ma[rt]<<endl;
34         return p;
35         }
36     int m=(l+r)>>1;
37     pair<int,int> lv(INF,0),rv(INF,0);
38     if(L<=m) lv=query(L,R,lson);
39     if(R>m) rv=query(L,R,rson);
40     pair <int,int> p;
41     p.first=min(lv.first,rv.first);
42     p.second=max(lv.second,rv.second);
43     return p;
44 }
45 int main(){
46     int n;int m;
47     cin>>n>>m;
48     build(1,n,1);
49     for(int i=1;i<=m;i++){
50         int a,b;
51         scanf("%d%d",&a,&b);
52         pair<int,int>p;
53         p=query(a,b,1,n,1);
54     //    cout <<p.second<<" "<<p.first<<"ss"<<endl;
55         printf("%d\n",p.second-p.first);
56     }
57     return 0;
58 }

猜你喜欢

转载自www.cnblogs.com/Msmw/p/11201293.html
今日推荐