Phillip and Trains

CodeForces - 586D