Tree-like array learning (one-dimensional)

Source: Internet
Author: User

Algorithm description

can query and modify a given sequence
Query: Mainly used to query the data between any two bits and
Modify: Modify a single data value
Time Complexity: Log (N)

Algorithmic thinking

1. Construction of arrays

Define Array C A
C1 = A1
C2 = A1 + A2
C3 = A3
C4 = A1 + A2 + A3 + A4
C5 = A5
C6 = A5 + A6
C7 = A7
C8 = A1 + A2 + A3 + A4 + A5 + A6 + A7 + A8
...
It is not difficult to see, in fact, the implementation of a data of the respective jurisdiction, CN, the jurisdiction of the number of n into a binary number, the end of a continuous number of 0; it can also be understood, so that 2^k <=n; The maximum value of K is the number of jurisdictions
Here is a method for finding 2^k, which will be used later

int lowbit(int x){    return//运用位运算及机器补码}

Call Lowbit (n) to derive the number of CN jurisdictions
And the CN jurisdiction is: N-lowbit (n) +1 to n

void make_tree(int n){    for(int i=1;i<=n;i++)    {        for(int j=i-lowbit(i)+1;j<=i;j++)        {            c[i]+=a[j];        }    }}

2. Summation

Make sum=0;
Traverse, each time the binary number of n is the last one 1 to 0, then sum + = C[n],n=n-lowbit (n), until n<=0;
The sum value is the sum of the sequence 1 ~ n

int make_sum(int n){    int sum=0;    while(n>0)    {        sum+=c[n];        n-=lowbit(n);    }    return sum;}

3. Modify individual data

Make changes to each CN containing AI

void modify(int n,int i,int num){    while(i<=n)    {        c[i]+=num-a[i];        i+=lowbit(i);    }}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Tree-like array learning (one-dimensional)

Related Article

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.