n, m = gets.split(" ").map{|s| s.to_i} r = [] m.times { r << gets.split(" ").map{|s| s.to_i} } class UnionFind def initialize(n) @par = 0.upto(n-1).to_a @rank = Array.new(n, 0) end def unite(x, y) x = find(x) y = find(y) return if x == y if @rank[x] < @rank[y] then @par[x] = y else @par[y] = x @rank[x] += 1 if @rank[x] == @rank[y] end end def same?(x, y) find(x) == find(y) end private def find(x) if @par[x] == x then x else @par[x] = find(@par[x]) end end end r.sort_by!{|x| -x[2]} v = Array.new(n) {Array.new} uf = UnionFind.new(n) maxd = 0 same = false while r.length > 0 do s, t, d = r.shift break if same and d < maxd maxd = d uf.unite(s-1, t-1) v[s-1] << t-1 v[t-1] << s-1 same = uf.same?(0, n-1) end dist = Array.new(n, Float::INFINITY) dist[0] = 0 q = [[0, 0]] cost = -1 while q.length > 0 and cost < 0 do cv, c = q.shift v[cv].each {|nv| if nv == n-1 then cost = c + 1 break end if dist[nv] > c + 1 dist[nv] = c + 1 q << [nv, c+1] end } end puts "#{maxd} #{cost}"