Under construction

Still being built. Things may change

Portal Game

Interview

Time limit1sMemory limit1024 MB

Summary
Find the minimum time to walk from cell 0 to cell N-1 when red portals must be taken and blue portals are optional, or report -1 if unreachable.
Level

Medium4 of 10

Topics
Shortest path, Graph
Solved
No attempts yet

Problem

Portal Game is played on a straight line. The line has NN cells numbered from 00 to N−1N-1. The goal is to start at cell 00 and reach cell N−1N-1 as quickly as possible.

The game has CC portals in total, and each portal is either red or blue. Each cell can hold at most one portal entrance. Using the portal whose entrance is at cell aia_i moves you to its exit at cell bib_i. Portals only work from entrance to exit, so you cannot use the same portal to go from bib_i back to aia_i.

Before reaching cell N−1N-1, you can take the following actions depending on the type of cell:

  • A cell with no portal entrance: move from the current cell xx to cell x+1x + 1, which takes 1 second.
  • A cell with a red portal entrance: use the red portal to move to its exit in 0 seconds.
  • A cell with a blue portal entrance: use the blue portal to move to its exit in 0 seconds, or move from cell xx to cell x+1x + 1, which takes 1 second.

Input

The first line contains the number of cells NN and the number of portals CC, separated by a space. (2≤N≤1052 \leq N \leq 10^5, 0≤C≤N0 \leq C \leq N)

Each of the next CC lines describes one portal. Each line contains three integers tit_i, aia_i, and bib_i, separated by spaces. tit_i is the type of the ii-th portal: ti=0t_i = 0 means red, and ti=1t_i = 1 means blue. aia_i and bib_i are the cell numbers of the entrance and exit of the ii-th portal. (ti∈{0,1}t_i \in \{0, 1\}, 0≤ai,bi≤N−10 \leq a_i, b_i \leq N-1, 0≤i≤C−10 \leq i \leq C-1)

No two portals share an entrance. That is, if 0≤i<j≤C−10 \leq i < j \leq C-1, then ai≠aja_i \neq a_j.

Output

Print the minimum time needed to start at cell 00 and reach cell N−1N-1 on the first line.

If no sequence of moves reaches cell N−1N-1, print −1-1.

Examples3

  1. Example 1

    Input
    10 2
    1 2 7
    0 6 3
    
    Expected output
    4
    
  2. Example 2

    Input
    14 3
    0 4 2
    1 5 6
    0 6 8
    
    Expected output
    -1
    
  3. Example 3

    Input
    6 3
    0 0 2
    1 1 4
    0 5 5
    
    Expected output
    3