Tree Array (binary index tree BIT Fenwick Tree) * "One-dimensional basic template" (Query interval and + modify update)

Source: Internet
Author: User

Rujia: "Training Guide" Page (194)


#include <stdio.h> #include <string.h> #include <stdlib.h> #include <algorithm>using namespace std;//One-dimensional tree-shaped array base template int lowbit (int x) {return x& (-X);} int c[1001];int sum (int x)//calculates the array elements from 1 to x and {int s=0; while (x>0) {s=s+c[x]; X=x-lowbit (x); } return s;} void Add (int x, int D)//will increase the value of a (x) by D, or you can subtract a value {while (x<=1000)///1000 Here is the cap of the array I opened, which is a change based on the data of the topic {c[x]=c[ X]+d; X=x+lowbit (x); }}int Main () {int a[1001]; int I, J; for (i=0; i<=1000; i++) {a[i]=i; } c[0]=0; for (I=1; i<=1000; i++)//have a[] array to calculate c[] array value {c[i]=0; For (J=i-lowbit (i) +1; j<=i; J + +) {C[i]=c[i]+a[j]; }//} int x; scanf ("%d", &x); printf ("%d\n", sum (x)); Query the 1->x of a[] and int y; scanf ("%d", &y); Add (x, y); A[] The element labeled X is increased by D printf ("%d\n", sum (x)); return 0;}

Tree Array (binary index tree BIT Fenwick Tree) * "One-dimensional base template" (query interval and + modify update)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.