一維樹狀數組區間更新區間查詢

來源:互聯網
上載者:User

標籤:ges   line   技術   set   include   分享   for   nbsp   div   

推理過程

維護兩個數組,d[i] = a[i] - a[i - 1],f[i] = i * d[i],剩下的,區間更新和區間查詢就和【一維樹狀數組區間更新單點查詢】一樣了。

實現原始碼

#include<iostream>#include<cstdio>#include<cstring>using namespace std;int n = 20;int a[40], d[40], f[40];int query(int* arr, int x) {    int res = 0;    for(int i = x; i > 0; i -= (i & -i))res += arr[i];    return res;}void update(int* arr, int x, int val) {    for(int i = x; i <= n; i += (i & -i))arr[i] += val;}inline int getsum(int x){    return (x + 1) * query(d, x) - query(f, x);}int main() {    memset(a, 0, sizeof(a));    memset(d, 0, sizeof(d));    memset(f, 0, sizeof(f));    for(int i = 1; i <= n; ++i) {        a[i] = i;        int t = a[i] - a[i - 1];        update(d, i, t);        update(f, i, t * i);    }    for(int i = 1; i <= n; ++i) {        printf("sum(%d) = %d\n", i, getsum(i));    }    puts("------------------------------------------");    int x = 1, y = 10, val = 20;    update(d, x, val);    update(d, y + 1, -val);    update(f, x, val * x);    update(f, y + 1, -val * (y + 1));    printf("sum(10) = %d\n", getsum(10));    return 0;}

 

一維樹狀數組區間更新區間查詢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.