In OI, the prefix and is an important optimization ideas
Function: seeking and static range
Template Title: input sequence \ (A_ 1..n} {\) , for each input tuple \ ((L, R & lt) \) , seeking \ (\ sum_ {i = l } ^ ra_i \)
First think about how to do simple arithmetic it
For each set of input \ ((L, R & lt) \) , traversal sequence \ (a_ {l..r} \) summation, as follows
int s(0);
for(int i(l);i<=r;++i)s+=a[i];
return s;
Time complexity: \(O(n)\)
Memory complexity: \(O(1)\)
If there are m times the query, the overall time complexity \ (O (nm) \)
Observe this process, you can find a large number of unnecessary operations, for example, ask for twice their range of intersection is to be redundant operation
Is there a method to reduce the amount of calculation makes it?
Can be found in \ (\ sum_ {i = l } ^ ra_i = \ sum_ {i = 1} ^ ra_i- \ sum_ {i = 1} ^ {l-1} a_i \)
That is, if the array is present \ (s_ {1..n} \) such that \ (S_I = \ sum_. 1} = {J ^ ia_j \) , then
\(\sum_{i=l}^ra_i=s_r-s_{l-1}\)
\ (s_ {1..n} \) isThe legendaryPrefix and an array of it!
Operation:
First: ordinary array \ (a_ {1..n} \) configured prefix and arrays \ (s_ {1..n} \)
Second: the input section \ ([L, R & lt] \) , and direct calculation of the interval \ (s_r-s_ {l- 1} \)
The key is how to construct a prefix and an array
Using recursive thought
\(s_i=\sum_{j-1}^ia_j=\sum_{j-1}^{i-1}a_j+a_i=s_{i-1}+a_i\)
code show as below
Seeking \ (s_ {1..n} \)
for(int i(1);i<=n;++i)s[i]=s[i-1]+a[i];
ask
return s[r]-s[l-1];
All basic operations prefix and so far have finished it!
Conclusion & Extension:
Prefix and a pan with high data structures, optimization of thinking is also very important
It uses a recursive pretreatment and method for reducing redundant calculation, to achieve optimization purposes, it is widely used in optimization dp
Applies not only to add, but also to all satisfied associative and has units (for addition is 0) and inverse binary operation (a is the inverse element -a), such as multiplication
But for the most value is less shy (for this kind of problem (called RMQ problem) also have a great algorithms)
Strong product prefix and thought: Fenwick tree
Particularly, the prefix and there is an inverse operation, called differential
So far this article on the successful conclusion of the matter, please Juan guys have a lot of advice and support, THX!