Editorial
Process the bridges in decreasing order of box size.
Let be the maximum number of boxes that can be collected when Lulu ends at island using only bridges whose box sizes are larger than the current bridge's size.
Suppose the current bridge connects and and has box size . If this bridge is used as the last bridge, every previously collected box must have size greater than . Therefore, all valid previous states are already represented in .
There are two possible transitions.
- Lulu is at island and crosses this bridge to island .
- Lulu is at island and crosses this bridge to island .
Thus we update:
However, the two updates must use the old values of and , so that the same bridge is not used twice during one transition.
Since all box sizes are distinct, we do not need to group bridges with equal sizes.
Each bridge is processed once, and sorting takes time. The total time complexity is , and the memory complexity is .