【UOJ 50】树状数组2

Description

如题,已知一个数列(下标从1开始计数),你需要进行下面两种操作:

1.将某区间每一个数,加上x

2.获取某一个数的值

Input

第一行包含两个整数N、M,分别表示该数列数字的个数和操作的总个数。

第二行包含N个用空格分隔的整数,第i个数字表示数列第i项的初始值。

接下来M行每行包含2或4个整数,表示一个操作,具体如下:

操作1: 格式:1 x y k 含义:将区间[x,y]内每个数加上k

操作2: 格式:2 x 含义:输出第x个数的值

Output

输出包含若干行整数,即为所有操作2的结果。

Sample Input

5 5
1 5 4 2 3
1 2 4 2
2 3
1 1 5 -1
1 3 5 7
2 4

Sample Output

6
10

Hint

时间:1s 空间:128M

对于30%的数据:N<=8,M<=10

对于70%的数据:N<=10000,M<=10000

对于100%的数据:N<=100000,M<=100000

题解:emm树状数组变形qwq

#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<cstdio>
typedef long long ll;
using namespace std;

ll tree[500005];
int n,m,x,y;
ll k;
int low(int x){
    return x&(-x);
}
void add(int x, ll num) {
    while(x<=n){
        tree[x]+=num;
        x+=low(x);
    }
}
ll biu(int x){
    ll ans = 0;
    while(x){
        ans+=tree[x];
        x-=low(x);
    }
    return ans;
}
int main() {
    freopen("50.in","r",stdin);
    freopen("50.out","w",stdout);
    scanf("%d %d",&n,&m);
    ll last=0,now;
    for(int i=1;i<=n;i++){
        scanf("%lld", &now);
        add(i,now-last);
        last=now;
    }
    int op;
    while(m--){
        scanf("%d", &op);
        if(op==1){
            scanf("%d %d %lld",&x,&y,&k);
            add(x,k); add(y+1,-k);
        } 
        if(op==2){
            scanf("%d",&x);
            printf("%lld
", biu(x));
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/wuhu-JJJ/p/11195842.html