Trains and Statistic

CodeForces - 675E