This page is still under construction.

Parts of this page are still being built. What you see may change.

Crosswalk

Time limit1sMemory limit1024 MB

Summary
Given a cyclic schedule of crosswalks that each turn green for one minute per cycle, find the earliest arrival time from area 1 to area N.
Level

Medium7 of 10

Topics
Graph, Shortest path, BFS, Math
Solved
No attempts yet

Problem

On your way home you have come across a busy intersection. This intersection has NN areas that people can pass through, and several crosswalks connecting these areas. Every area is connected to every other, directly or indirectly, through crosswalks. For convenience, number the NN areas from 11 to NN.

You analyzed the intersection's signals from afar, so you know the order in which the crosswalks get a green light. A signal cycle lasts MM minutes, and the signal changes every minute. The 1+i1+i-th signal of each cycle (0≤i<M0 \le i < M) starts at minutes i,M+i,2M+i,3M+i,⋯i, M+i, 2M+i, 3M+i, \cdots and for 11 minute gives a green light to the crosswalk connecting area AiA_i and area BiB_i, while every other crosswalk gets a red light. The same crosswalk can get a green light several times within one cycle.

When a crosswalk has a green light, you can use it to move to the area on the other side, and the move takes 11 minute. The signal must not turn red while you are crossing, so if the signal is green during time s∼es \sim e, you must start crossing the crosswalk during time s∼e−1s \sim e-1.

Given the crosswalks and the signal information, write a program that finds the minimum time needed to get from area 11 to area NN, starting at minute 00.

Input

The first line gives the number of areas NN and the signal cycle length MM, separated by a space.

Of the MM lines starting from the second line, the 1+i1+i-th line gives the two endpoints AiA_i and BiB_i of the crosswalk that gets a green light for 11 minute starting at minutes i,M+i,2M+i,3M+i,⋯i, M+i, 2M+i, 3M+i, \cdots, separated by a space.

Output

On the first line, print the minimum time in minutes needed to get from area 11 to area NN.

Constraints

  • 2≤N≤100 0002 \leq N \leq 100\,000
  • 1≤M≤700 0001 \leq M \leq 700\,000
  • 1≤Ai,Bi≤N1 \leq A_i, B_i \leq N (0≤i<M)(0 \le i < M)
  • Ai≠BiA_i \ne B_i (0≤i<M)(0 \le i < M)
  • Every area is connected to every other, directly or indirectly, through crosswalks.
  • All numbers in the input are integers.

Examples2

  1. Example 1

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

    Input
    8 12
    3 4
    5 6
    7 8
    2 3
    1 5
    4 8
    1 2
    6 7
    2 3
    7 8
    1 2
    6 7
    
    Expected output
    18