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_macros, non_snake_case)]
use std::cmp::{max, min, Ordering};
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};

//{{{ macros missing in 1.15.1
#[macro_use]
mod macros {
    macro_rules! eprint {
        ($($t:tt)*) => {{
            use ::std::io::Write;
            let _ = write!(::std::io::stderr(), $($t)*);
        }};
    }
    macro_rules! eprintln {
        () => { eprintln!(""); };
        ($($t:tt)*) => {{
            use ::std::io::Write;
            let _ = writeln!(::std::io::stderr(), $($t)*);
        }};
    }
    macro_rules! dbg {
        ($val:expr) => {
            match $val {
                tmp => {
                    eprintln!(
                        "[{}:{}] {} = {:#?}",
                        file!(),
                        line!(),
                        stringify!($val),
                        &tmp
                    );
                    tmp
                }
            }
        };
    }
}
//}}}

#[derive(Clone)]
struct Edge {
    src: usize,
    dst: usize,
    id: usize,
}

#[derive(Copy, Clone, Eq, PartialEq)]
struct State {
    cost: usize,
    town: usize,
    id: usize,
}

impl Ord for State {
    fn cmp(&self, other: &State) -> Ordering {
        let a = other.cost.cmp(&self.cost);
        if a != Ordering::Equal {
            return a;
        }
        let a = self.town.cmp(&other.town);
        if a != Ordering::Equal {
            return a;
        }
        self.id.cmp(&other.id)
    }
}

impl PartialOrd for State {
    fn partial_cmp(&self, other: &State) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

fn run() {
    let stdin = std::io::stdin();
    let mut sc = Scanner::new(stdin.lock());
    let n: usize = sc.read();
    let m: usize = sc.read();
    let mut edges: Vec<Vec<Edge>> = vec![Vec::new(); n];
    let mut edges_map: Vec<HashMap<usize, Vec<Edge>>> = vec![HashMap::new(); n];
    for _ in 0..m {
        let p: usize = sc.read::<usize>() - 1;
        let q: usize = sc.read::<usize>() - 1;
        let c: usize = sc.read();
        edges[p].push(Edge {
            src: p,
            dst: q,
            id: c,
        });
        edges_map[p]
            .entry(c)
            .or_insert_with(|| Vec::new())
            .push(Edge {
                src: p,
                dst: q,
                id: c,
            });
        edges[q].push(Edge {
            src: q,
            dst: p,
            id: c,
        });
        edges_map[q]
            .entry(c)
            .or_insert_with(|| Vec::new())
            .push(Edge {
                src: q,
                dst: p,
                id: c,
            });
    }

    let mut queue = BinaryHeap::new();
    let mut sets = vec![HashSet::new(); n];
    for &id in edges_map[0].keys() {
        queue.push(State {
            cost: 1,
            town: 0,
            id: id,
        });
    }
    let mut reached = false;
    while let Some(State { cost, town, id }) = queue.pop() {
        if town == n - 1 {
            println!("{}", cost);
            reached = true;
            break;
        }
        if sets[town].contains(&id) {
            continue;
        }
        sets[town].insert(id);
        if sets[town].len() == 1 {
            for e in &edges[town] {
                let nstate = State {
                    cost: cost + if e.id == id { 0 } else { 1 },
                    town: e.dst,
                    id: e.id,
                };
                if !sets[e.dst].contains(&e.id) {
                    queue.push(nstate);
                }
            }
        } else if edges_map[town].contains_key(&id) {
            for e in &edges_map[town][&id] {
                let nstate = State {
                    cost: cost + if e.id == id { 0 } else { 1 },
                    town: e.dst,
                    id: e.id,
                };
                if !sets[e.dst].contains(&e.id) {
                    queue.push(nstate);
                }
            }
        }
    }
    if !reached {
        println!("-1");
    }
}

fn main() {
    std::thread::Builder::new()
        .name("run".to_string())
        .stack_size(1024 * 1024 * 1024)
        .spawn(run)
        .unwrap()
        .join()
        .unwrap()
}

//{{{ Scanner
pub struct Scanner<R> {
    reader: R,
}

impl<R> Scanner<R> {
    pub fn new(r: R) -> Scanner<R> {
        Scanner { reader: r }
    }
}

fn is_whitespace(b: u8) -> bool {
    b == b' ' || b == b'\n' || b == b'\r' || b == b'\t'
}

impl<R: std::io::Read> Scanner<R> {
    pub fn read<T: std::str::FromStr>(&mut self) -> T {
        let buf = std::io::Read::bytes(self.reader.by_ref())
            .map(|b| b.expect("Read failed"))
            .skip_while(|&b| is_whitespace(b))
            .take_while(|&b| !is_whitespace(b))
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error")
    }

    pub fn read_vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read()).collect()
    }

    pub fn read_chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
}
//}}}