class UnionFind def initialize(size) @parent = Array.new(size, -1) @rank = Array.new(size, 0) end def root(x) if @parent[x] < 0 return x else @parent[x] = root(@parent[x]) return @parent[x] end end def same(x, y) return root(x) == root(y) end def unite(x, y) x = root(x) y = root(y) if x == y return end if @rank[x] < @rank[y] x, y = y, x end @parent[x] += @parent[y] @parent[y] = x if @rank[x] == @rank[y] @rank[x] += 1 end end def size(x) return -@parent[root(x)] end end n, q = gets.chomp.split(" ").map(&:to_i) p = gets.chomp.split(" ").map(&:to_i) uf = UnionFind.new(n) n.times do |i| if p[i] != -1 uf.unite(i, p[i] - 1) end end q.times do a, b = gets.chomp.split(" ").map(&:to_i) if uf.same(a - 1, b - 1) puts "Yes" else puts "No" end end