zoukankan      html  css  js  c++  java
  • G

    题意 给出一个序列  每次查询区间的max-min是多少 

    思路:直接维护max 和min即可  写两个query分别查最大最小值

     1 #include<cstdio>
     2 #include<algorithm>
     3 #include<set>
     4 #include<vector>
     5 #include<cstring>
     6 #include<iostream>
     7 using namespace std;
     8 const int maxn=5e4+5;
     9 int a[maxn];
    10 struct Node{
    11     int l,r,maxnum,minnum;
    12 }tree[maxn*4];
    13 void push_up(int x){
    14     tree[x].maxnum=max(tree[x<<1].maxnum,tree[x<<1|1].maxnum);
    15     tree[x].minnum=min(tree[x<<1].minnum,tree[x<<1|1].minnum);
    16 }
    17 int  query1(int x,int l,int r){
    18     int L=tree[x].l,R=tree[x].r;
    19     if(l<=L&&R<=r){
    20         return tree[x].maxnum;
    21     }
    22     else {
    23         int mid=L+R>>1;
    24         int ans=0;
    25         if(l<=mid)ans=max(ans,query1(x<<1,l,r));
    26         if(mid<r)ans=max(ans,query1(x<<1|1,l,r));
    27         return ans;
    28     }
    29 }
    30 int  query2(int x,int l,int r){
    31     int L=tree[x].l,R=tree[x].r;
    32     if(l<=L&&R<=r){
    33         return tree[x].minnum;
    34     }
    35     else {
    36         int mid=L+R>>1;
    37         int ans=1e7;
    38         if(l<=mid)ans=min(ans,query2(x<<1,l,r));
    39         if(mid<r)ans=min(ans,query2(x<<1|1,l,r));
    40         return ans;
    41     }
    42 }
    43 void build(int x,int l,int r){
    44     tree[x].l=l,tree[x].r=r;
    45     if(l==r){
    46         tree[x].maxnum=tree[x].minnum=a[l];
    47     }
    48     else {
    49         int mid=l+r>>1;
    50         build(x<<1,l,mid);
    51         build(x<<1|1,mid+1,r);
    52         push_up(x);
    53     }
    54 }
    55 int main(){
    56     int n,q;
    57     scanf("%d%d",&n,&q);
    58     for(int i=1;i<=n;i++)scanf("%d",&a[i]);
    59     build(1,1,n);
    60     for(int i=1;i<=q;i++){
    61         int x,y;
    62         scanf("%d%d",&x,&y);
    63         printf("%d
    ",query1(1,x,y)-query2(1,x,y));
    64     }
    65     return 0;
    66 }
  • 相关阅读:
    java-多个数的和
    大道至简第二章
    大道至简第一章感悟上
    Tools
    LruCache
    Fragment
    科普指纹识别
    Python使用MySQL数据库
    Eclipse中添加PyDev插件
    UniversalAndroidImageLoader出现异常:ImageLoader: Unable to resolve host "https": No address associated with host
  • 原文地址:https://www.cnblogs.com/ttttttttrx/p/10301724.html
Copyright © 2011-2022 走看看