Nu aveti permisiuni pentru a descarca fisierul grader_test50.ok
Diferente pentru blog/square-root-trick intre reviziile #102 si #80
Nu exista diferente intre titluri.
Diferente intre continut:
p. The naive solution uses an array. It takes $O(1)$ time for an update and $O(hi - lo) = O(n)$ for the range sum.
p.A more efficient solution splits the array into length $k$ slices and stores the slice sums in an array $S$.
A more efficient solution splits the array into length $k$ slices and stores the slice sums in an array $S$.
p.The update takes constant time, because we have to update the value for A and the value for the corresponding $S$.The queryis interesting. The elementsofthe first andlast slice (partially contained in thequeried range) have to be traversedone byone, butfor slices completely contained in ourrange we can use the valuesin $S$ directlyandget aperformance boost.
The update takes constant time, because we have to update the value for A and the value for the corresponding $S$.
!<{margin-right: 20px; auto;display:block;}blog/square-root-trick?image01.png!
p. Here is an update example:
!{margin-right: 20px; auto;display:block;}blog/square-root-trick?image01.png!
The query is interesting. Slices completely contained in our range are summed up fast. The elements of the first and last slice (partially contained in the queried range) have to be traversed one by one.
p. In $update(6, 5)$ we have to change$A[6]$to5 which results in changing the valueof $S[1]$ tokeep $S$up to date.
!<{margin-right: 20px; auto;display:block;}blog/square-root-trick?image00.png!
!{margin-right: 20px; auto;display:block;}blog/square-root-trick?image00.png!
In $query(2, 14)$ we get
== code(c) |
query(2, 14) = A[2] + A[3]+
(A[4] + A[5] + A[6] + A[7]) +
(A[8] + A[9] + A[10] + A[11]) +
A[12] + A[13] + A[14]
= A[2] + A[3] +
S[1] + S[2] +
A[12] + A[13] + A[14]
= 0 + 7 + 11 + 9 + 5 + 2 + 0
= 34
==
Here's how the code looks:
p. The code looks like this:
== code(c) | def update(S, A, i, k, x):
return s ==
Each query takeson average$k/2+ n/k + k/2= k + n/k$ time.Thisis minimizedfor$k=sqrt(n)$.Sowegeta $O(sqrt(n))$ timecomplexity query.
The query takes less than $k + n/k + k = 2k + n/k$ time. $2k + n/k$ is minimized when $k$ is $O(sqrt(n))$. For $k = sqrt(n)$ the query takes $O(sqrt(n))$ time.
This trick also works for other associative operations, like: min, gcd, product etc.
Diferente intre securitate:
protected
public
