Meeting Time
Time limit1sMemory limit256 MB
Bessie and Elsie each choose a downhill route from field 1 to field N with their own edge times so both arrive at the same earliest moment.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Graph
- Solved
- No attempts yet
Problem
Bessie and her sister Elsie want to travel from the barn to their favorite field. They want to leave the barn at exactly the same moment and reach the field at exactly the same moment.
The farm has fields () numbered through . Field holds the barn and field is the favorite field. The farm sits on the side of a hill, so field is higher than field whenever . There are paths, each joining a pair of fields. Every path is steep enough that a cow can follow it only downhill. A path joining field and field can be followed from to but not the other way, because that direction is uphill. At most one path joins any pair of fields, so .
Bessie and Elsie need different amounts of time on the same path. One path might cost Bessie units of time and Elsie . The cows spend time only while walking a path. They are in a hurry, so they cross a field in zero time and never wait anywhere.
Find the smallest total time in which Bessie and Elsie can reach their favorite field at the same moment.
Input
The first line contains and , separated by a space.
Each of the next lines describes one path with four integers , , , . Fields and are the fields the path joins, with . The value is the time Bessie needs on that path and is the time Elsie needs. Both and are between and .
Output
Print, on a single line, the minimum time in which both cows reach the favorite field at the same moment. If no such time exists, or if the cows cannot reach field at all, print IMPOSSIBLE on a single line. When the barn is already the favorite field, so print .
Hint
In the first example Bessie is twice as fast as Elsie on every path. Even so, if Bessie walks 1 -> 2 -> 3 and Elsie walks 1 -> 3, they arrive at the same moment.