Train Trip
Time limit4sMemory limit1024 MB
Given N cities, each with a train covering an interval [L_i, R_i] that contains city i, find the fewest train rides from U to V, or -1 if impossible.
- Level
Medium6 of 10
- Topics
- Shortest path, Array, Greedy
- Solved
- No attempts yet
Problem
Jaemin is worn out by the complicated, exhausting life at Gyeonggi Science High School, so he decides to leave for somewhere else. He sets off on a very long trip to Songjuk Kingdom to look for a quiet resort.
Songjuk Kingdom is a peaceful country with cities in a row. The cities are numbered from 1 at the far end up to .
Jaemin plans to travel on the Songjuk Train, a popular tourist attraction in the kingdom. Each city has one kind of train, and each train runs along its own fixed route. Specifically, the train departing from city runs on a circular line that passes through every city from city to city , where . A passenger can get off at any city while the train is passing through, but cannot board a train partway through its route.
During the trip, Jaemin makes travel plans. The -th plan is to travel from city to city using only the Songjuk Train.
Jaemin wants to save both time and money, so he wants to change trains as few times as possible in each plan. Your task is to determine whether each travel plan can be carried out using only trains, and if so, find the minimum number of trains he must ride.
Input
The first line contains and , separated by a space.
The next lines each contain and , separated by a space.
The next lines each contain and , separated by a space.
Output
For each travel plan, print the minimum number of trains that must be ridden to carry it out, one per line, for a total of lines. If a plan cannot be carried out using only trains, print -1 instead of the number of trains.