Mo's Algorithm with bitset
bitset is often used for decision and counting problems that are difficult to maintain with conventional data structures, while Mo's algorithm can maintain interval information that is hard to handle with regular data structures. Combining the two allows leveraging the advantages of both.
Example 「Ynoi2016」Falling into the Rabbit Hole
This problem fits the characteristics of combining Mo's algorithm with bitset as mentioned above. It is natural to think of using bitset to store all distinct values that appear in each interval. The answer for a set of queries is the sum of the lengths of all intervals minus the number of elements in the union of the three sets multiplied by \(3\).
However, when using bitset with Mo's algorithm, adjustments must be made to account for the features of bitset:
- bitset does not handle multiple occurrences of the same value well. We can insert into the bitset the discretized value of the current element plus the current count of its occurrences in the interval.
- When using Mo's algorithm, we might not pay attention to the order of the four pointer movement methods, which can lead to situations where the left pointer is to the right of the right pointer, resulting in a negative interval length and thus a negative count of elements. This usually doesn't matter in other cases, but in this problem, the elements inserted into the bitset depend on the count, so we must be careful about the order of the four pointer movements. We should write the statements that move the left and right pointers to the left and right first to avoid inserting negative numbers into the bitset.
- Although bitset uses little space, it still struggles with data of size \(10 ^ 5 \times 10 ^ 5\). Therefore, we need to split the queries into constant-sized blocks and process them separately, ensuring that the space usage is just enough while keeping the time complexity unchanged.
Reference Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | |
Exercises
本页面最近更新:,更新历史
发现错误?想一起完善? 在 GitHub 上编辑此页!
本页面贡献者:OI-wiki
本页面的全部内容在 CC BY-SA 4.0 和 SATA 协议之条款下提供,附加条款亦可能应用