题解 | #A Simple Problem with Integers#

A Simple Problem with Integers

https://ac.nowcoder.com/acm/problem/51100

思路

线段树板子。

代码

#include<iostream>
#define pushup(x) (tree[x]=tree[x<<1]+tree[x<<1|1])
#define MID int mid=(start+end)>>1
using namespace std;
const int maxn=1e6+7;
typedef long long ll;
ll tree[maxn<<2],lazy[maxn<<2];
int n,q,a,b,c,arr[maxn];
int ch;

void pushdown(int node,int start,int end){
    if(start==end) return;
    MID;
    if(lazy[node]){
        lazy[node<<1]+=lazy[node];
        lazy[node<<1|1]+=lazy[node];
        tree[node<<1]+=(ll)(mid-start+1)*lazy[node];
        tree[node<<1|1]+=(ll)(end-mid)*lazy[node];
        lazy[node]=0;
    }
}

void build(int node,int start,int end){
    if(start==end){
        tree[node]=arr[start];
        return;
    }
    MID;
    build(node<<1,start,mid);
    build(node<<1|1,mid+1,end);
    pushup(node);
}

void update(int node,int start,int end,int l,int r,int val){
    if(l<=start&&end<=r){
        tree[node]+=(ll)(end-start+1)*val;
        lazy[node]+=val;
        return;
    }
    MID;
    pushdown(node,start,end);
    if(l<=mid) update(node<<1,start,mid,l,r,val);
    if(r>mid) update(node<<1|1,mid+1,end,l,r,val);
    pushup(node);
}

ll query(int node,int start,int end,int l,int r){
    if(l<=start&&end<=r) return tree[node];
    MID;
    pushdown(node,start,end);
    ll res=0;
    if(l<=mid) res+=query(node<<1,start,mid,l,r);
    if(r>mid) res+=query(node<<1|1,mid+1,end,l,r);
    return res;
}

signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    cin>>n>>q;
    for(int i=1;i<=n;i++) cin>>arr[i];
    build(1,1,n);
    for(int i=1;i<=q;i++){
        //cin>>ch;
        char tt;cin>>tt;
        if(tt=='C'){
            cin>>a>>b>>c;
            update(1,1,n,a,b,c);
        }
        if(tt=='Q'){
            cin>>a>>b;
            cout<<query(1,1,n,a,b)<<endl;
        }
    }
    return 0;
}
全部评论

相关推荐

昨天 11:02
中山大学 C++
字节刚oc,但距离九月秋招很近了有两段互联网实习,非腾讯字节。不敢赌转正,现在在纠结去还是不去如果实习俩月离职会有什么后果吗
阿城我会做到的:不去后悔一辈子,能否转正取决于ld的态度,只要他不卡,答辩就是走流程,个人觉得可以冲一把
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
ohs的小木屋:比不少实习待遇高了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
05-28 12:15
点赞 评论 收藏
分享
叶扰云倾:进度更新,现在阿里云面完3面了,感觉3面答得还行,基本都答上了,自己熟悉的地方也说的比较细致,但感觉面试官有点心不在焉不知道是不是不想要我了,求阿里收留,我直接秒到岗当阿里孝子,学校那边的房子都退租了,下学期都不回学校,全职猛猛实习半年。这种条件还不诱人吗难道 然后现在约到了字节的一面和淘天的复活赛,外加猿辅导。华为笔试完没动静。 美团那边之前投了个base广州的,把我流程卡麻了,应该是不怎么招人,我直接简历挂了,现在进了一个正常的后端流程,还在筛选,不知道还有没有hc。
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务