Editorial for COCI '12 Contest 2 #6 Inspektor
Submitting an official solution before solving the problem yourself is a bannable offence.
Basic idea
Let us divide the offices into blocks such that each block contains consecutive offices. If the companies inside a block are organized in a certain data structure (which we will describe later), moving a company in or out can be accomplished by changing a single block, that is, with complexity . Mirko's stroll from to can be solved by manually checking the ending portions of the interval which do not form a complete block (there will be at most such checks), and solving the remaining blocks, that are completely contained in (there are at most such blocks), by querying the corresponding structures. The total complexity of a stroll is then . In the complexity formulas above, "" represents the complexity of operation on the data structure.
The data structure
Let us begin by calculating the account balance of company on day :
Notice that the function mapping time to balance is linear, so our structure needs to support queries to find the line with the largest value for a given coordinate (in our case, ).
This can be done by constructing an upper convex hull of the lines and then using ternary search to find the maximum value for a given .
However, since the value (time) in consecutive queries is increasing, the maximum-valued line 'role' will also move from left to right, so it is sufficient to keep a pointer to the currently maximum-valued line and, given a new , increment it while the next line to the right has a greater value for .
In order to construct an upper convex hull out of the lines in time , where is the number of lines, we need to have the lines sorted by the coefficient multiplying (the slope).
Therefore, our structure will keep track of:
- the sorted array of lines,
- the upper convex hull formed by those lines,
- the pointer to the currently maximum-valued line.
Deleting and inserting a line is done by traversing the sorted array, adding the new line and deleting the old one, which can both be done in . After that, we reconstruct the convex hull and reset the pointer to the first line in the hull.
The complexity of a single query cannot be predicted since it depends on the position of the pointer on the hull, but we can be certain that the pointer will be incremented at most times (until it reaches the last line) before the next convex hull rebuild, which resets it. Therefore, if is the number of pointer resets (i.e. insert and delete queries), the total complexity of all queries on block is .
Total complexity
Each operation of moving a company in (and moving the existing company out) requires changing a single block with complexity , while the total complexity of all queries is the sum of query complexities for all blocks: . Since the sum of is at most , the complexity equals . The total complexity is then ; if we select , this equals .
Comments