Under construction

Still being built. Things may change

Drifting

Interview

Time limit2sMemory limit1024 MB

Summary
Find the minimum weight path from vertex 1 to vertex N in a DAG where certain consecutive edge pairs (a, b, c) are forbidden.
Level

Medium5 of 10

Topics
Graph, Shortest path, Hash map
Solved
No attempts yet

Problem

You are given a weighted directed graph with NN vertices and MM edges. The ii-th edge goes from vertex uiu_i to vertex viv_i with weight wiw_i. Every edge satisfies ui<viu_i < v_i.

You are also given KK triples of integers. The ii-th triple is (ai,bi,ci)(a_i, b_i, c_i) with ai<bi<cia_i < b_i < c_i.

You start at vertex 11 and move along edges until you reach vertex NN. If you move directly from aia_i to bib_i, your next move must go to a vertex other than cic_i.

Determine whether vertex NN can be reached. If it can, find the minimum total weight of the edges you pass through.

Input

The first line contains NN and MM. Each of the next MM lines contains uiu_i, viv_i, and wiw_i. The next line contains KK. Each of the next KK lines contains aia_i, bib_i, and cic_i.

Output

If vertex NN cannot be reached, print −1-1. Otherwise, print the minimum total weight of the edges you pass through.

Constraints

  • 3≤N≤2×1053 \le N \le 2 \times 10^5
  • 0≤M≤2×1050 \le M \le 2 \times 10^5
  • 1≤ui<vi≤N1 \le u_i < v_i \le N for all ii
  • No two edges have the same (ui,vi)(u_i, v_i)
  • 1≤wi≤1091 \le w_i \le 10^9
  • 0≤K≤2×1050 \le K \le 2 \times 10^5
  • 1≤ai<bi<ci≤N1 \le a_i < b_i < c_i \le N for all ii

Hint

In the first sample, the best route is 1→3→41 \rightarrow 3 \rightarrow 4. In the second sample, the best route is 1→2→4→6→71 \rightarrow 2 \rightarrow 4 \rightarrow 6 \rightarrow 7.

Examples3

  1. Example 1

    Input
    4 4
    1 2 1
    1 3 2
    2 4 2
    3 4 2
    1
    1 2 4
    
    Expected output
    4
    
  2. Example 2

    Input
    7 8
    1 2 5
    1 3 2
    2 4 1
    3 4 1
    4 5 6
    4 6 2
    5 7 1
    6 7 1
    2
    2 4 5
    3 4 6
    
    Expected output
    9
    
  3. Example 3

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