Summary of the---tree array + reverse order to the problem.

Source: Internet
Author: User

Cough, this map must be ....

First, when there is a very large number of arrays, we may change the value of a a[i], require a[n, and all add up, is undoubtedly the time complexity of O (n).

But if n is very large, O (n) time complexity is sure to kneel, so, what to do, with a magical tree-like array.

The tree-like array code is simple, but very powerful! More exciting is that its time complexity value requires O (LOGN)!!!

Well, the first thing is to put the c[n] to show out, how to do it, the code is as follows:

int lowbit (int  t) {    return t& (-t);}

This code, simple to explode, but can be the jurisdiction of each c[i] to find out! (specifically with binary)

Then, after changing a certain value, it is necessary to update c[i], of course, after using c[n], the number of arrays has changed from N to Logn!

So, we use the Updata function:

void updata (int l,int  k) {     while (l<=N)     {           c[l]  +=k; //         l+=lowbit (l);  //    }}

Finally, there is a sum function:

int sum (int  k) {       int s=0;         while (k>0)     {           s+ =C[k];           K-= Lowbit (k);      }    Renturn s;}

Of course, a tree-like array can be used for reverse order, which is a very efficient code:

 for (i=1; i<=n;i++) {      updata (c[i],1);      Ans+=sum (n)-sum (C[i]);} // Don't ask me why, I don't know ...

Summary of the---tree array + reverse order to the problem.

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: 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.