2018/2/17 Daily One Learning tree array

Source: Internet
Author: User

Tree-like array

What is a tree-like array??

See


Where A[i] is a single element value, C[i] is a tree-like array.

It's not hard to find c[1]=a[1],c[2]=a[1]+a[2],c[3]=a[3]

where 1 = (01) 2, 2 = (10) 2,3= (11) 2

OK, we found C[i]=a[i-2<<k+1]+......+a[i] (k is the lowest bit in the I binary to the highest consecutive 0 numbers)

So, what is the way to quickly find out 2<<k?

Notice the binary (????) for a number of x. 100000 ... It is known that the number of 0 must be K. Then this 1 (and at the very end of 1) represents the decimal digit 2<<k.

Okay, so how do you find the 1 position??

Here we think of anti-code, bitwise take counter plus 1, pay attention to add one!!! Then there must be the original code at the end of the 1 corresponding binary location of the inverse code is also 1 (think, why?) )

So 2<<k=x&-x, that's it. We resolved how to modify the C array.

So what does a tree-like array do?

Ask for the interval and!!

How can I ask?

For example, ask A[3]+......+a[6]

We use the prefix and the idea is to seek sum[6]-sum[2], then how to seek sum[x]?

Look at the code:

int sum (int  x) {int res=0;  while (x>0) res+=c[x],x-=x&-x; return Res;}

See while (x>0) res+=c[x],x-=x&-x; It is not difficult to find that sum is going from the current point to the left.

What if I want to make x+d?

Look at the code:

void Add (int x,int  d) {while (x<=n) c[x]+=d,x+=x&- x;}

See X+=x&-x, know is to go right.

Have you learned it?

2018/2/17 Daily One Learning tree array

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.