Under construction

Still being built. Things may change

Movable Type Graph

Time limit1.5sMemory limit1024 MB

Summary
Find the shortest path from vertex 1 to vertex 2 in graph T, where each graph can embed earlier graphs as sub-blocks with chosen entry and exit vertices.
Level

Hard8 of 10

Topics
Graph, Shortest path, Dynamic programming
Solved
No attempts yet

Problem

In the Goryeo period, the scholar Ha Uibi made graphs by printing them with metal movable type. While doing this, Ha Uibi became curious about the shortest path in a type graph, the name for a graph printed with type.

Ha Uibi currently has TT type graphs, numbered from 1 to TT in the order they were made.

Type graph tt has NtN_t numbered vertices, from 1 to NtN_t. Type graph tt is then completed by repeatedly doing one of the following.

  • Add a directed edge with weight from vertex vv to vertex ww.
  • Print the ii-th type graph so that its start and end points are vertices vv and ww of graph tt. Its vertices and edges are added to graph tt. The vertices of the printed ii-th graph are not numbered. (1≤i<t1 \le i < t)

The start vertex of every type graph is vertex 1, and its end vertex is vertex 2.

Find the shortest path from vertex 1 to vertex 2 in type graph TT.

Input

The first line contains the number of type graphs TT. (1≤T≤100 0001 \le T \le 100\,000)

The information for each type graph is given as follows.

Suppose you are reading type graph tt.

  • The first line contains the number of numbered vertices NtN_t and the number of edge or sub-graph operations MtM_t, separated by a space. (2≤Nt≤200 0002 \le N_t \le 200\,000, 0≤Mt≤500 0000 \le M_t \le 500\,000)
  • The next MtM_t lines each contain three integers vv, ww, and xx, separated by spaces. (1≤v,w≤Nt1 \le v, w \le N_t, v≠wv \ne w, −(t−1)≤x≤109-(t-1) \le x \le 10^9)
    • If x≥0x \ge 0, a directed edge with weight xx from vertex vv to vertex ww was added.
    • If x<0x < 0, the type graph ∣x∣|x| was printed with its start point at vertex vv and its end point at vertex ww.

The sum of the numbered vertex counts does not exceed 200 000200\,000. The sum of the edge and sub-graph operation counts does not exceed 500 000500\,000.

Output

Print the length of the shortest path from vertex 1 to vertex 2 in type graph TT. If there is no path from vertex 1 to vertex 2, or if this value is greater than 101810^{18}, print -1.

Examples1

  1. Example 1

    Input
    2
    4 5
    1 3 5
    1 4 2
    4 3 2
    3 2 3
    4 2 7
    5 7
    1 3 4
    3 4 2
    4 1 6
    3 5 3
    4 5 8
    3 2 -1
    5 2 7
    
    Expected output
    11