Feeding Time
Time limit1sMemory limit128 MB
Given N cows in a fixed order with upper and lower bound distance constraints, find the maximum possible distance between cow 1 and cow N, or report impossibility or unboundedness.
- Level
Medium7 of 10
- Topics
- Shortest path, Graph, Greedy, Implementation
- Solved
- No attempts yet
Problem
The cows line up in a single row in order of their numbers to wait for their food. Sunyeong owns cows (), numbered from to . Because the cows stand in increasing order of their numbers, if is the coordinate of cow , then . Two or more cows may stand at the same coordinate.
Cows that like each other want to stay within a certain distance, while cows that dislike each other want to stay at least a certain distance apart. You are given a list of length () describing pairs of cows that like each other together with the maximum distance the two may be apart, followed by a list of length () describing pairs of cows that dislike each other together with the minimum distance the two must be apart.
Write a program that, if the cows can be lined up so that all of these conditions hold, computes the maximum possible distance between cow and cow .
Input
The first line contains the integers , , and , separated by spaces.
Each of the next lines contains three integers , , and (), meaning that cow and cow may be at most () apart.
Each of the following lines contains three integers , , and (), meaning that cow and cow must be at least () apart.
Output
Print the maximum distance between cow and cow on the first line. Print if it is impossible to line the cows up under the given conditions, or if the maximum distance can be arbitrarily large (infinite).