Submarine in the Rybinsk Sea (hard edition)

CodeForces - 1195D2