Feeding Time

Time limit1sMemory limit128 MB

Summary
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 NN cows (2≤N≤1,0002 \le N \le 1{,}000), numbered from 11 to NN. Because the cows stand in increasing order of their numbers, if xix_i is the coordinate of cow ii, then x1≤x2≤⋯≤xNx_1 \le x_2 \le \cdots \le x_N. 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 MLML (1≤ML≤10,0001 \le ML \le 10{,}000) describing pairs of cows that like each other together with the maximum distance the two may be apart, followed by a list of length MDMD (1≤MD≤10,0001 \le MD \le 10{,}000) 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 11 and cow NN.

Input

The first line contains the integers NN, MLML, and MDMD, separated by spaces.

Each of the next MLML lines contains three integers AA, BB, and DD (1≤A<B≤N1 \le A < B \le N), meaning that cow AA and cow BB may be at most DD (1≤D≤1,000,0001 \le D \le 1{,}000{,}000) apart.

Each of the following MDMD lines contains three integers AA, BB, and DD (1≤A<B≤N1 \le A < B \le N), meaning that cow AA and cow BB must be at least DD (1≤D≤1,000,0001 \le D \le 1{,}000{,}000) apart.

Output

Print the maximum distance between cow 11 and cow NN on the first line. Print −1-1 if it is impossible to line the cows up under the given conditions, or −2-2 if the maximum distance can be arbitrarily large (infinite).

Examples3

  1. Example 1

    Input
    4 2 1
    1 3 10
    2 4 20
    2 3 3
    
    Expected output
    27
    
  2. Example 2

    Input
    3 1 1
    1 3 5
    1 3 10
    
    Expected output
    -1
    
  3. Example 3

    Input
    3 1 1
    1 2 5
    2 3 3
    
    Expected output
    -2