【Tree array】Analysis

tree array

Below a represents the original array, and c represents the tree array
树状数组功能:

1.给某个位置上的数加上一个数  
2.快速的求前缀和

c[x]层数的确定:

看x的二进制表示末尾有几个0,有几个0就是第几层

c[x]含义表示:

lowbit(x) = 2^k (k 是x二进制表示末尾0的个数)
c[x] 表示在A数组中一段区间的和 :c[x] =  ( x - 2^k, x] = ( x - lowbit(x), x]

insert image description here
1. Add a number to the number at a certain position

// 当前点是x,父节点是x + lowbit(x),若给x加上v,父节点都要同时加上v
a[x] += v;
for (int i = x; i <= n; i += lowbit(i)) c[i] += v;

2. Quickly find the prefix sum

int res = 0;
for (int i = x; i > 0; i -= lowbit(i)) res += c[i];

Example: Find the sum of continuous intervals dynamically

Given a sequence of n numbers, two operations are specified, one is to modify a certain element, and the other is to obtain the continuous sum of the sub-sequence [a,b].

input format

The first line contains two integers n and m, which respectively represent the number of numbers and the number of operations.

The second line contains n integers, representing the complete sequence.

Next m lines, each line contains three integers k, a, b (k=0, means finding the sum of the subsequence [a,b]; k=1, means adding b to the ath number).

Sequences are counted from 1.

output format

Output several rows of numbers, which represent the continuous sum of the corresponding sub-sequences [a,b] when k=0.

data range

1 ≤ n ≤ 100000,
1 ≤ m ≤ 100000,
1 ≤ a ≤ b ≤ n,
data guarantee that at any time, the sum of all elements in the array is within the range of int.

Input sample:

10 5
1 2 3 4 5 6 7 8 9 10
1 1 5
0 1 3
0 4 8
1 7 5
0 4 8

Sample output:

11
30
35
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 100010;
int a[N], c[N];
int n, m;
int lowbit(int x)
{
    
    
    return x & -x;
}
// 在x的位置上加上v
void add(int x, int v)
{
    
    
    for (int i = x; i <= n; i += lowbit(i)) c[i] += v;
}
// 查询1 - x位置的和
int query(int x)
{
    
    
    int res = 0;
	for (int i = x; i > 0; i -= lowbit(i)) res += c[i];
    return res;
}

int main()
{
    
    
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i ++) scanf("%d", &a[i]);
    for (int i = 1; i <= n; i ++) add(i, a[i]);
    while (m --)
    {
    
    
        int k, x, y;
        scanf("%d%d%d", &k, &x, &y);
        if (k == 0) printf("%d\n", query(y) - query(x - 1));
        else add(x, y);
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/laaa123mmm/article/details/129413642