Here’s a link to the problem.
The first thing we should consider is how to solve the problem without any updates. Naively, we enumerate all possible paths in time. However, note that simply writing nested loops recomputes a ton of redundant information.
In particular, if, for a node , there are paths from node 1 to node that use edges and paths from node to node that use edges, our loop takes to process all of these paths, when we could instead determine the shortest path in by picking the shortest path on both sides.
This motivates a divide-and-conquer approach. If, for every node , we determine the shortest paths from to and from to which each use exactly edges (we assume is even for convenience), we can determine the shortest path from to which uses edges in time by enumerating the path’s midpoint.
Thus, we can write the following recurrence relation for time complexity:
where denotes the time complexity of finding the shortest path between a fixed pair of nodes which uses exactly edges. The factor of 2 arises from the fact that we must find the shortest path both from and to , and the factor of is from enumerating all midpoints.
Solving the recurrence relation with base case , we get , and substituting , this is . So far, so good; but how do we handle updates?
First, as is typical of graph problems which involve deleting edges, we consider reversing the order of operations. Thus, we just need to figure out how to support adding edges, where each edge is added exactly once.
Intuitively, not too much information changes after adding a single edge; we now just have to quantify exactly how much “not too much” is.
Note that our divide-and-conquer structure means that the answer to our problem can change only when the answers to its left/right subproblems change. This crucial property of DNQ is also what allows segment trees to work so quickly. You can thus think of DNQ structures as a method to bundle information in a way such that as much information is preserved between updates as possible.
Going back to our problem, we can write another recurrence relation for the total number of times our states will change:
where represents the time it takes to process the change of a single substate. Luckily for us, for all (hopefully you understand why!), and as well (since each edge is added exactly once) so in fact, we have
Therefore, our DNQ approach will still run in time, even with updates!