Problem:
Score : 600 points

Problem Statement

Snuke's town has a subway system, consisting of N stations and M railway lines. The stations are numbered 1 through N. Each line is operated by a company. Each company has an identification number.

The i-th ( 1 \leq i \leq M ) line connects station p_i and q_i bidirectionally. There is no intermediate station. This line is operated by company c_i.

You can change trains at a station where multiple lines are available.

The fare system used in this subway system is a bit strange. When a passenger only uses lines that are operated by the same company, the fare is 1 yen (the currency of Japan). Whenever a passenger changes to a line that is operated by a different company from the current line, the passenger is charged an additional fare of 1 yen. In a case where a passenger who changed from some company A's line to another company's line changes to company A's line again, the additional fare is incurred again.

Snuke is now at station 1 and wants to travel to station N by subway. Find the minimum required fare.

Constraints

2 \leq N \leq 10^5

0 \leq M \leq 2×10^5

1 \leq p_i \leq N (1 \leq i \leq M)

1 \leq q_i \leq N (1 \leq i \leq M)

1 \leq c_i \leq 10^6 (1 \leq i \leq M)

p_i \neq q_i (1 \leq i \leq M)

Input

The input is given from Standard Input in the following format:

N M
p_1 q_1 c_1
:
p_M q_M c_M

Output

Print the minimum required fare. If it is impossible to get to station N by subway, print -1 instead.

Sample Input 1

3 3
1 2 1
2 3 1
3 1 2

Sample Output 1

1

Use company 1's lines: 1 → 2 → 3. The fare is 1 yen.

Sample Input 2

8 11
1 3 1
1 4 2
2 3 1
2 5 1
3 4 3
3 6 3
3 7 3
4 8 4
5 6 1
6 7 5
7 8 5

Sample Output 2

2

First, use company 1's lines: 1 → 3 → 2 → 5 → 6. Then, use company 5's lines: 6 → 7 → 8. The fare is 2 yen.

Sample Input 3

2 0

Sample Output 3

-1

Solution in Rust (1.15.1) (judge verdict: Accepted)

#![allow(unused_imports, unused_variables, dead_code)]
use std::io::*;
use std::fmt::*;
use std::str::*;
use std::cmp::*;
use std::collections::*;

trait InputValue {
    fn parse(s: &str) -> Self;
}

fn read<T: InputValue>() -> T {
    let mut buf = String::new();
    let _ = stdin().read_line(&mut buf);
    T::parse(&buf.trim())
}

fn readnc<T: InputValue>() -> Vec<T> {
    let mut vec = vec![];
    let line: String = read();
    for token in line.split_whitespace() {
        vec.push(T::parse(token));
    }
    vec
}

fn readn<T: InputValue>(n: usize) -> Vec<T> {
    let mut vec = vec![];
    for _ in 0..n {
        vec.push(read());
    }
    vec
}

macro_rules! parse_single_value {
    ($($t:ty),*) => {
        $(
            impl InputValue for $t {
                fn parse(s: &str) -> $t { s.parse().unwrap() }
            }
        )*
	}
}
parse_single_value!(i32, i64, f32, f64, usize, String);

macro_rules! parse_tuple {
	($($t:ident),*) => {
		impl<$($t),*> InputValue for ($($t),*) where $($t: InputValue),* {
			fn parse(s: &str) -> ($($t),*) {
				let mut tokens = s.split_whitespace();
				let t = ($($t::parse(tokens.next().unwrap())),*);
				t
			}
		}
	}
}
parse_tuple!(A, B);
parse_tuple!(A, B, C);

// ===

const INF: i32 = 100000000;

fn main() {
    let (n, m): (usize, usize) = read();
    let edges: Vec<(usize, usize, usize)> = readn(m);
    let mut station_companies: Vec<HashSet<usize>> = vec![HashSet::new(); n];

    let mut code_map = HashMap::new();
    for &(p, q, c) in &edges {
        station_companies[p-1].insert(c);
        station_companies[q-1].insert(c);

        let code = station_code(p-1, c);
        if !code_map.contains_key(&code) {
            let len = code_map.len();
            code_map.insert(code, n + len);
        }

        let code = station_code(q-1, c);
        if !code_map.contains_key(&code) {
            let len = code_map.len();
            code_map.insert(code, n + len);
        }
    }

    let vn = code_map.len() + n;
    let mut graph: Vec<Vec<(usize, i32)>> = vec![vec![]; vn];

    // between station
    for &(p, q, c) in &edges {
        let u = find_code(p-1, c, &code_map);
        let v = find_code(q-1, c, &code_map);
        graph[u].push((v, 0));
        graph[v].push((u, 0));
    }

    // terminal and station
    for u in 0..n {
        for &cid in &station_companies[u] {
            let v = find_code(u, cid, &code_map);
            graph[u].push((v, 1));
            graph[v].push((u, 0));
        }
    }

    let mut dp: Vec<i32> = vec![INF; vn];
    dp[0] = 0;

    let mut heap = BinaryHeap::new();
    heap.push((0, 0));
    while let Some(head) = heap.pop() {
        let current_cost = -head.0;
        if dp[head.1] < current_cost {
            continue
        }
        for &(to, cost) in &graph[head.1] {
            let to_cost = current_cost + cost;
            if dp[to] > to_cost {
                dp[to] = to_cost;
                heap.push((-to_cost, to));
            }
        }
    }


    if dp[n-1] == INF {
        println!("-1");
    } else {
        println!("{}", dp[n-1]);
    }
}

fn find_code(station_id: usize, company_id: usize, map: &HashMap<usize, usize>) -> usize {
    let station = station_code(station_id, company_id);
    *map.get(&station).unwrap()
}

fn station_code(station_id: usize, company_id: usize) -> usize {
    station_id * 1000001 + company_id
}