N = gets.to_i skills = (N - 1).times.map { gets.split.map(&:to_i) } Q = gets.to_i M = Q.times.map { gets.split.map(&:to_i) } level_table = Hash.new skill_table = Hash.new E = Array.new(N + 1) { [] } skills.each.with_index(2) do |(l, a), idx| E[a] << [idx, l] end dp = Array.new(N + 1, -1) dp[1] = 0 queue = [] queue << [1, 0] levels = [Float::INFINITY] until queue.empty? t, l = queue.shift dp[t] = l levels << l E[t].each do |nt, nl| if l < nl queue << [nt, nl] else queue << [nt, l] end end end levels.sort! M.each do |t, v| if t == 1 cnt = levels.bsearch_index { |l| l > v } puts cnt else puts dp[v] end end