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: Wrong Answer)

#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;

fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}

fn make_island(
    lines: &HashMap<usize, Vec<(usize, usize)>>,
    n: usize,
) -> (HashMap<(usize, usize), usize>, usize) {
    let mut island_count = 1usize; // 0 has already used for start.
    let mut island_dict: HashMap<(usize, usize), usize> = HashMap::new();
    for &company in lines.keys() {
        let mut uft = UnionFindTree::new(n);
        for &(s, t) in lines[&company].iter() {
            uft.unite(s, t);
        }

        for &(s, t) in lines[&company].iter() {
            let parent = uft.find(s);
            if !island_dict.contains_key(&(company, parent)) {
                island_dict.insert((company, parent), island_count);
                island_count += 1;
            }
            let parent_island = island_dict[&(company, uft.find(s))];
            island_dict.insert((company, s), parent_island);
            island_dict.insert((company, t), parent_island);
            assert_eq!(parent, uft.find(t));
        }
    }
    (island_dict, island_count)
}

fn make_island_edges(
    island_dict: &HashMap<(usize, usize), usize>,
    island_len: usize,
    station_to_company_dict: &Vec<Vec<usize>>,
) -> Vec<Vec<Edge>> {
    let mut edges = vec![HashSet::new(); island_len];
    for station_idx in 0..station_to_company_dict.len() {
        for ci1 in 0..station_to_company_dict[station_idx].len() {
            let company1 = station_to_company_dict[station_idx][ci1];
            for ci2 in ci1..station_to_company_dict[station_idx].len() {
                let company2 = station_to_company_dict[station_idx][ci2];
                if company1 == company2 {
                    continue;
                }
                let island1 = island_dict[&(company1, station_idx)];
                let island2 = island_dict[&(company2, station_idx)];
                assert!(island1 != island2);
                edges[island1].insert(island2);
                edges[island2].insert(island1);
            }
        }
    }
    let mut edges2 = vec![Vec::new(); island_len];
    for i in 0..island_len {
        edges2[i] = edges[i]
            .iter()
            .map(|&x| Edge { to: x, cost: 1 })
            .collect::<Vec<_>>();
    }
    edges2
}

fn main() {
    let v: Vec<usize> = read_vec();
    let (n, m) = (v[0], v[1]);
    let mut lines = HashMap::new();

    let mut station_to_company_dict = vec![HashSet::new(); n];
    for _ in 0..m {
        let v: Vec<usize> = read_vec();
        let (s, t, c) = (v[0] - 1, v[1] - 1, v[2]);
        lines.entry(c).or_insert(Vec::new()).push((s, t));
        station_to_company_dict[s].insert(c);
        station_to_company_dict[t].insert(c);
    }
    let mut station_to_company_dict2 = vec![Vec::new(); n];
    for i in 0..station_to_company_dict.len() {
        station_to_company_dict2[i] = station_to_company_dict[i]
            .iter()
            .cloned()
            .collect::<Vec<_>>();
    }
    station_to_company_dict2[0].push(0);
    /*

    let (mut island_dict, island_len) = make_island(&lines, n);
    island_dict.insert((0, 0), 0); // insert start island.
                                   // println!("island_dict {:?}", island_dict);
                                   // println!("station_to_company_dict2 {:?}", station_to_company_dict2);

    let edges = make_island_edges(&island_dict, island_len, &station_to_company_dict2);
    let d = dijkstra(&edges, 0, island_len);

    let mut ans = INF;
    for &company in station_to_company_dict2[n - 1].iter() {
        let goal_island = island_dict[&(company, n - 1)];
        ans = min(ans, d[goal_island]);
    }
    if ans == INF {
        println!("-1");
    } else {
        println!("{}", ans);
    }
    */
}

#[derive(Debug, Clone)]
struct UnionFindTree {
    parent: Vec<isize>,
    size: Vec<usize>,
    height: Vec<u64>,
}

impl UnionFindTree {
    fn new(n: usize) -> UnionFindTree {
        UnionFindTree {
            parent: vec![-1; n],
            size: vec![1usize; n],
            height: vec![0u64; n],
        }
    }

    fn find(&mut self, index: usize) -> usize {
        if self.parent[index] == -1 {
            return index;
        }
        let cur_parent = self.parent[index] as usize;
        let ret = self.find(cur_parent);
        self.parent[index] = ret as isize;
        ret
    }

    fn same(&mut self, x: usize, y: usize) -> bool {
        self.find(x) == self.find(y)
    }

    fn get_size(&mut self, x: usize) -> usize {
        let root = self.find(x);
        self.size[root as usize]
    }

    fn unite(&mut self, index0: usize, index1: usize) -> bool {
        let a = self.find(index0);
        let b = self.find(index1);
        if a == b {
            false
        } else {
            if self.height[a] > self.height[b] {
                self.parent[b] = a as isize;
                self.size[a] += self.size[b];
            } else if self.height[a] < self.height[b] {
                self.parent[a] = b as isize;
                self.size[b] += self.size[a];
            } else {
                self.parent[b] = a as isize;
                self.size[a] += self.size[b];
                self.height[a] += 1;
            }
            true
        }
    }
}

const INF: i32 = std::i32::MAX;

#[derive(PartialEq, Debug)]
struct MinInt {
    value: i32,
}

impl Eq for MinInt {}

impl PartialOrd for MinInt {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        other.value.partial_cmp(&self.value)
    }
}

impl Ord for MinInt {
    fn cmp(&self, other: &MinInt) -> Ordering {
        other.value.cmp(&self.value)
    }
}

fn make_pair(x: i32, y: usize) -> (MinInt, usize) {
    (MinInt { value: x }, y)
}

#[derive(Debug, Clone)]
struct Edge {
    to: usize,
    cost: i32,
}

fn dijkstra(edges: &Vec<Vec<Edge>>, start_idx: usize, num_apexes: usize) -> Vec<i32> {
    let mut d = vec![INF; num_apexes];
    d[start_idx] = 0;
    let mut que = BinaryHeap::new();
    que.push(make_pair(0, start_idx));

    while let Some((u, v)) = que.pop() {
        if d[v] < u.value {
            continue;
        }
        for e in &edges[v] {
            if d[e.to] > d[v] + e.cost {
                d[e.to] = d[v] + e.cost;
                que.push(make_pair(d[e.to], e.to));
            }
        }
    }
    d
}