zoukankan      html  css  js  c++  java
  • 树状数组

    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!

  • 相关阅读:
    关于Update语句在不同数据库中的差别
    MSIL指令速查表
    一个对于博客园的建议
    代码风格关于if语句
    关于Page.cs文件中注释的一点补充
    在Java、C#和C++中遍历集合
    BPEL4WS的开源Java实现
    【Linux】linux固定ip
    【Linux】【MySQL】MySQL主从数据库
    wpf 写个简单的控件吧
  • 原文地址:https://www.cnblogs.com/yszhyhm/p/13365591.html
Copyright © 2011-2022 走看看