Differential & prefix and

We start from the problem.

 

One problem: the number n has been assigned, there are m instruction, each time the number of k required to add a, the final evaluation of all the numbers.

$1 ≤ k ≤ n,m ≤ 10^5$.

In fact, this problem can be serviced by an array.

 

Second problem: the number n has been assigned, there are m instruction, each time the requested number to the second x-y plus the number a, the final evaluation of all the numbers.

$1 ≤ x ≤ y ≤ n,m ≤ 10^5$

In fact, this title block, tree line, Fenwick tree and other algorithms are too many of these questions.

But look at the next question:

 

Three issues: the number n has been assigned, there are m instruction, each time the requested number to the second x-y plus the number a, the final evaluation of all the numbers.

$1 ≤ x ≤ y ≤ n,m ≤ 5*10^6$

We found that: 5e6 this range is too great, O (n log n) as well as slower complexity can not be had.

So, into our subject: the difference.

 


 

The difference

① What is the difference?

Difference is a skill a constant complexity mark achieved by summation and inquiries.

Generally suitable for static maintenance (front before adding, final evaluation).

 

② Differential how to use?

We'll give you an example:

There are a number of columns:

    . 1   . 9 2. 8. 6. 5. 4. 3. 7 
Tag: 0 0 0 0 0 0 0 0 0 // now there is no tag marked

Now, we are the third number to the number 5 plus 2.

Then we discovered that the first three numbers can start all the numbers followed by 2, and then start from number 6 to number all minus 2 behind it, it is equivalent to the third number to the number 5 plus the 2.

So then mark:

A [I]:   1   . 9   2   . 8   . 3   . 7   . 4   . 6   . 5 
Tag:   0   0   2   0   0   -2 0   0   0   // flag marked 1 *

Then, we then number 4 to number 8 minus 1.

According to the above ideas, we can start from the number 4, behind all the numbers minus 1, starting with the first nine numbers all the numbers followed by 1.

A [I]:   . 1   . 9   2   . 8   . 3   . 7   . 4   . 6   . 5 
Tag:   0   0   2 -1   0 -2   0   0   . 1   // marked marked * 2

Assume command execution ends, then we sum this:

With a record sum array, tag number and brought before $ i $ sum_i representatives.

a[i]    :  1  9  2  8  3  7  4  6  5
tag     :  0  0  2 -1  0 -2  0  0  1  
sum[i] : 0 0 2 1 1 -1 -1 -1 0

Finally, we add the $ a_i $ corresponding to $ sum_i $ sum, is the answer.

Time complexity of O (n).

Guess you like

Origin www.cnblogs.com/zengpeichen/p/11279207.html