結果

問題 No.2316 Freight Train
ユーザー amentorimaru
提出日時 2023-03-26 21:31:59
言語 Ruby
(3.4.1)
結果
AC  
実行時間 745 ms / 2,000 ms
コード長 902 bytes
コンパイル時間 234 ms
コンパイル使用メモリ 7,424 KB
実行使用メモリ 33,920 KB
最終ジャッジ日時 2024-09-19 10:00:41
合計ジャッジ時間 20,018 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 26
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

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
0