Avoiding Airports
Time limit3sMemory limit512 MB
Find a flight itinerary from country 1 to country n minimizing the sum of squared waiting times at airports.
- Level
Hard8 of 10
- Topics
- Graph, Shortest path, Dynamic programming, Sorting
- Solved
- No attempts yet
Problem
David is planning a trip around the world. He can visit countries, and flights are available to him. Flight leaves country at time and lands in country at time .
David is in the airport of country at time , and he wants to reach country . The total time the trip takes does not bother him, but he hates waiting in an airport. Waiting units of time in an airport gives him units of frustration. The time he spends in the airport of country from time until his first flight departs counts as waiting too.
Find an itinerary that minimizes the total frustration.
Input
The first line contains two space separated integers and . (, )
Each of the next lines contains four space separated integers , , , and . (, ) This describes a flight from country to country that departs at time and lands at time .
A flight might have the same departure and arrival country.
No two flights have the same departure time, and no two flights have the same arrival time. No flight has the same arrival time as the departure time of another flight. There is always a way for David to reach country .
Output
Print the minimum total frustration on a single line.
Hint
In the first example the cheapest itinerary is this one.
- The fifth flight of the input. It goes from country to country , departing at time and landing at time .
- The third flight. It goes from country to country , departing at time and landing at time .
- The seventh flight. It goes from country to country , departing at time and landing at time .
- The eighth flight. It goes from country to country , departing at time and landing at time .
The four waits cost , , , and , so the total frustration is . Another itinerary gets David to his destination sooner, but its total frustration is higher.