Editorial for Dream and the Multiverse
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
This problem effectively asks us to support queries of an arbitrary subrectangle of the transitive closure of the given DAG.
Consider how we would solve the problem if there were only one query of the form . We will use an array of bitsets:
- The -th element of the -th bitset is if, and only if, there exists a path from to .
- The -th element of the -th bitset is always .
- The -th bitset is formed by taking the bitwise OR of all its adjacent nodes, in topological order.
The time complexity of this is , with a space complexity of . We can reduce the space complexity to linear by processing the nodes in chunks of length , that is, only storing the nodes in that any node can reach, and iterating through .
Consider how to extend this to interval queries. If we query , then we want the number of 1's in the subrectangle formed with opposite corners and . Keeping in mind the chunk borders, we can separate the subrectangle into seven regions:
| | |
aaa|dddd|dddd|eee
aaa|dddd|dddd|eee
aaa|dddd|dddd|eee
====+====+====+====
bbb|dddd|dddd|fff
bbb|dddd|dddd|fff
bbb|dddd|dddd|fff
bbb|dddd|dddd|fff
====+====+====+====
bbb|dddd|dddd|fff
bbb|dddd|dddd|fff
bbb|dddd|dddd|fff
bbb|dddd|dddd|fff
====+====+====+====
ccc|dddd|dddd|ggg
ccc|dddd|dddd|ggg
ccc|dddd|dddd|ggg
| | |
The number of 's in the regions can be calculated with one popcount loop each, contributing to the time complexity.
Consider what happens when we shrink each chunk into one element, whose number of 's is easily calculated by a popcount per element:
| | |
|d|d|
|d|d|
|d|d|
-+-+-+-
|d|d|
|d|d|
|d|d|
|d|d|
-+-+-+-
|d|d|
|d|d|
|d|d|
|d|d|
-+-+-+-
|d|d|
|d|d|
|d|d|
| | |
To calculate the number of 's in the region, we do a two-dimensional prefix sum on the popcount of each row of each chunk, contributing to the time complexity.
Lastly, we need to deal with and . We can't calculate them directly, but we can transpose the graph - and along with it the transitive closure matrix - and then deal with them in the same way we deal with 's.
The total time complexity is with linear memory usage.
Comments