(+ Segment tree different update intervals (each node update value)) HDOJ-4027

Can You answer these queries?

HDOJ-4027

  • This question and do in front of a slightly different topic. Previous topic update interval of time are unified update, which is updating the same value. But not the same here, where each leaf node updates a different change.
  • Taking into account also the maximum 64-bit number, so even plus square root operation, also open up to 7 times, where it can be transferred to the update function, each leaf node when walked for square root operation .
  • In the update function there is one detail to note is that when all the leaf nodes of the current node is included in 1, you can not update down, direct return.
  • query function is still the same as before, nothing new.
  • On this question, the subject of casual working also need to pay attention to the format of the output. There is x, y not explicitly say less than, and would therefore need to sort.
//区间修改(不同于统一修改,这里是区间中每一项修改的值都不一样)和区间查询
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn=100005;
int n,m;
long long dur[maxn];
long long sums[maxn<<2];
void pushup(int id,int l,int r){
    int lc=id<<1;
    int rc=id<<1|1;
    sums[id]=sums[lc]+sums[rc];
}
void build(int id,int l,int r){
    if(l==r){
        sums[id]=dur[l];
        return;
    }
    int mid=(l+r)>>1;
    int lc=id<<1;
    int rc=id<<1|1;
    build(lc,l,mid);
    build(rc,mid+1,r);
    pushup(id,l,r);
}
void update(int id,int l,int r,int p,int q){
    if(sums[id]==r-l+1){//当结点覆盖的叶子结点全是1,也就是说sum等于覆盖的长度时返回,不用继续计算。
        return;
    }
    if(l==r){
        sums[id]=sqrt(sums[id]);
        return;
    }
    int mid=(l+r)>>1;
    if(p<=mid){
        update(id<<1,l,mid,p,q);
    }
    if(q>mid){
        update(id<<1|1,mid+1,r,p,q);
    }
    pushup(id,l,r);
}
long long query(int id,int l,int r,int p,int q){
    long long sum=0;
    if(p<=l&&q>=r){
        return sum=sums[id];
    }
    int mid=(l+r)>>1;
    int lc=id<<1;
    int rc=id<<1|1;
    if(p<=mid){
        sum+=query(lc,l,mid,p,q);
    }
    if(q>mid){
        sum+=query(rc,mid+1,r,p,q);
    }
    return sum;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int k=0;
    while(cin>>n){
        for(int i=1;i<=n;i++){
            cin>>dur[i];
        }
        build(1,1,n);
        cin>>m;
        cout<<"Case #"<<++k<<":"<<endl;
        for(int i=0;i<m;i++){
            int t,p,q;
            cin>>t>>p>>q;//不保证p<q
            int temp=p;
            p=min(p,q);
            q=max(temp,q);
            if(t==0){//update
                update(1,1,n,p,q);
            }else{//query
                cout<<query(1,1,n,p,q)<<endl;
            }
        }
        cout<<endl;
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/GarrettWale/p/11448479.html