Acwing 242.一個簡單的的整數問題 —— 差分樹狀陣列(簡單版)
阿新 • • 發佈:2020-12-29
題目連結:https://www.acwing.com/problem/content/248/
1 #include <iostream> 2 #include <algorithm> 3 #include <cstring> 4 #include <cstdio> 5 6 using namespace std; 7 8 typedef long long LL; 9 const int N = 1e5 + 10; 10 int a[N]; 11 LL tr[N]; 12 int n, m; 13 14 int lowbit(intx) 15 { 16 return x & -x; 17 } 18 19 void add(int x, int k) 20 { 21 for (int i = x; i <= n; i += lowbit(i)) tr[i] += k; 22 } 23 24 LL sum(int x) 25 { 26 LL res = 0; 27 for (int i = x; i ; i -= lowbit(i)) res += tr[i]; 28 return res; 29 } 30 31 int main() 32 { 33 scanf("%d%d", &n, &m); 34 35 for (int i = 1; i <= n; i ++ ) scanf("%d", &a[i]); 36 37 for (int i = 1; i <= n; i ++ ) add(i, a[i] - a[i - 1]); 38 39 while (m -- ) 40 { 41 char op[2]; int l, r, k; 42 scanf("%s%d", op, &l); 43 44 if (*op == 'C') 45 { 46 scanf("%d%d", &r, &k); 47 add(l, k), add(r + 1, -k); 48 } 49 else 50 { 51 printf("%lld\n", sum(l)); 52 } 53 } 54 55 return 0; 56 }
此題將字首和線段樹改為了差分樹狀陣列,即每個點存的是a[i] - a[i - 1]。
由此我們可知道,若
樹狀陣列儲存的是差分,那sum得到的是修改後陣列中的一個值;
樹狀陣列儲存的是原陣列,那sum得到的是修改後陣列的字首和。