版本比较
[Tutorial] Square root decomposition and applications 洛谷镜像
正文
增加 2 行删除 2 行
10 行未改动1112131415151617181940 行未改动60616263646465666768220 行未改动全部展开10 行未改动
Answering queries on a static array, offline (Mo's algorithm)---
Consider a problem where we are asked to find the answer for certain intervals $[l,r]$. We can't quickly compute the answer for an arbitrary interval, but we know how to transition to $[l,r\pm1]$ and $[l\pm1,r]$ fast given some information remaining from $[l,r]$ answer calculation. The number of transitions we need to do to get from $[l_1,r_1]$ to $[l_2,r_2]$ is $|l_1-l_2|+|r_1-r_2|$. Consider a problem where we are asked to find the answer for certain intervals $[l,r]$. We can't quickly compute the answer for an arbitrary interval, but we know how to transition to $[l,r\pm1]$ and $[l\pm1,r]$ fast given some information remaining from $[l,r]$ answer calculation. The number of transitions we need to do to get from $[l_1,r_1]$ to $[l_2,r_2]$ is $|l_1-l_2|+|r_1-r_2|$.
If there are only two intervals we need to answer such transitioning wouldn't help us. However, if there are *many* intervals, choosing a good transitioning route will drastically reduce the total time needed. Finding the best transition route quick is allegedly NP-hard, so we will focus on estimating a "good enough" route.
Consider the following scheme for 2D Manhattan TSP: We do square root decomposition on the $x$ coordinate, separating the grid into vertical blocks, $n$ cells tall and $B$ cells wide. There are $n/B$ such blocks.40 行未改动In the following we will look at some examples.
### Range distinct query (SPOJ DQUERY)
Statement: Given a static array and queries of the form $[l,r]$, count the number of different values that occur between $[l,r]$. Statement: Given a static array and queries of the form $[l,r]$, count the number of different values that occur between $[l,r]$.
The naive transition is intuitive: we maintain a table $v$ where $v[x]$ is the number of times $x$ occured in the interval that we are maintaining. When adding an element $x$ such that $v[x]=0$, increment the answer; when deleting an element $x$ such that $v[x]=1$, decrement the answer.
**However**, this needs many random accesses to this table, which is very cache-unfriendly, leading to a massive constant. Can we do better?220 行未改动全部展开