树状数组

Single point modification, interval query

the code is follow

#include <cstdio>
#include <iostream>
#define lowbit(x) x&-x
using namespace std;

const int N = 5e5+10;

int n, m;
int a[N], tree[N<<2];

inline void chenge (int x, int val) {
   for (int i = x; i <= n; i += lowbit(i))
      tree[i] += val;
}

inline int ask (int x) {
   int res = 0;
   while (x) {
      res += tree[x];
      x -= lowbit(x);
   }
   return res;
}

int main () {
   scanf ("%d%d", &n, &m);
   for (int i = 1; i <= n; ++ i) {
      scanf ("%d", &a[i]);
      chenge (i, a[i]);
   }
   for (int i = 1; i <= m; ++ i) {
      int opt, x, k;
      scanf ("%d%d%d", &opt, &x, &k);
      if (opt == 1) chenge (x, k);
      else cout << ask(k)-ask(x-1) << '
';
   }
   return 0;
}

and the Interval modification, single point query

the code is follow:

#include <bits/stdc++.h>
#define lowbit(x) x&-x
using namespace std;

const int N = 5e5+10;

int n, m, s;
int a[N], tree[N];

inline void chenge (int x, int val) {
   for (int i = x; i <= n; i += lowbit(i))
      tree[i] += val;
}

inline int ask (int x) {
   int res = 0;
   while (x) {
      res += tree[x];
      x -= lowbit(x);
   }
   return res;
}

main () {
   cin >> n >> m;
   for (int i = 1; i <= n; ++ i) {
      scanf ("%d", &a[i]);
      chenge (i, a[i]-s);
      s = a[i];
   }
   for (int i = 1; i <= m; ++ i) {
      int opt, x, y, k;
      scanf ("%d", &opt);
      if (opt == 1) {
         scanf ("%d%d%d", &x, &y, &k);
         chenge (x, k);
         chenge (y+1, -k);
      } else scanf ("%d", &x), cout << ask(x) << '
';
   }
   return 0;
}

PS

1.s must from zero

2.the tree array is so easy!

原文地址:https://www.cnblogs.com/yszhyhm/p/13365591.html