线段树生成—每日算法档

  • Post author:
  • Post category:其他


在这里插入图片描述

#include<bits/stdc++.h>
using namespace std;
int n;
int a[100000];
int tree[4*10000];
void build(int p, int l, int r){
    if(l==r){
        tree[p] = a[l];
        return ;
    }
    int mid = (l+r)/2;
    build(p*2,l, mid);
    build(p*2+1,mid+1,r);
    tree[p] = tree[2*p]+ tree[2*p+1];
}
void change(int p , int l , int r, int pos, int num){
    if( l==r){
        tree[p] = tree[p]+num;
        return;
    }
    int mid = (l+r)/2;
    if(pos <= mid){
        change(p*2,l,mid, pos, num);
    }else{
        change(pos*2+1, mid+1, r, pos, num);
    }
}
int calc(int p, int l, int r, int x, int y){
    if(x<=1 && r<y){
        return tree[p];
    }
    int mid = (l+r)/2;
    int ans = 0;
    if(x<=mid) {
        ans = ans+calc(p*2, 1, mid , x, y);
    }
    if(y>mid){
        ans = ans + calc(p*2+1,mid+1,r, x,y);
    }
    return ans;
}
int main(){
    scanf("%d",&n);
    for (int i = 1; i <=n ; i++)
    {
        scanf("%d",&a[i])
    }
    build(1,1,n);
    for (int i = 1; i <= n; i++)
    {
        int x,y,z;
        scanf("%d%d%d", &x, &y, &z);
        if(x==1){
            change(1,1,n,y,z);
        }
        else{
            cout << calc(1,1,n,y,z) <<endl;
        }
    }
    
    
    return 0;
}



版权声明:本文为qq_44417051原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。