結果

問題 No.2316 Freight Train
ユーザー simansiman
提出日時 2023-05-28 10:13:40
言語 Ruby
(3.3.0)
結果
AC  
実行時間 695 ms / 2,000 ms
コード長 896 bytes
コンパイル時間 51 ms
コンパイル使用メモリ 11,352 KB
実行使用メモリ 35,624 KB
最終ジャッジ日時 2023-08-27 06:21:00
合計ジャッジ時間 17,197 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 79 ms
15,056 KB
testcase_01 AC 73 ms
15,272 KB
testcase_02 AC 73 ms
15,200 KB
testcase_03 AC 677 ms
35,108 KB
testcase_04 AC 405 ms
26,448 KB
testcase_05 AC 332 ms
26,252 KB
testcase_06 AC 141 ms
16,308 KB
testcase_07 AC 490 ms
20,560 KB
testcase_08 AC 494 ms
35,488 KB
testcase_09 AC 516 ms
30,388 KB
testcase_10 AC 515 ms
26,744 KB
testcase_11 AC 531 ms
34,652 KB
testcase_12 AC 587 ms
33,932 KB
testcase_13 AC 695 ms
35,512 KB
testcase_14 AC 694 ms
35,528 KB
testcase_15 AC 688 ms
35,472 KB
testcase_16 AC 691 ms
35,596 KB
testcase_17 AC 686 ms
35,564 KB
testcase_18 AC 676 ms
35,504 KB
testcase_19 AC 693 ms
35,508 KB
testcase_20 AC 691 ms
35,624 KB
testcase_21 AC 683 ms
35,400 KB
testcase_22 AC 680 ms
35,508 KB
testcase_23 AC 571 ms
35,512 KB
testcase_24 AC 637 ms
35,512 KB
testcase_25 AC 518 ms
34,792 KB
testcase_26 AC 505 ms
34,852 KB
testcase_27 AC 394 ms
15,304 KB
testcase_28 AC 82 ms
14,988 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

class UnionFind
  def initialize(n)
    @size = Array.new(n, 1)
    @rank = Array.new(n, 0)
    @parent = []

    (0..n).each do |i|
      @parent[i] = i
    end
  end

  def find(x)
    if @parent[x] == x
      x
    else
      @parent[x] = find(@parent[x])
    end
  end

  def unite(x, y)
    x = find(x)
    y = find(y)
    return if x == y

    if @rank[x] < @rank[y]
      @parent[x] = y
      @size[y] += @size[x]
    else
      @parent[y] = x
      @size[x] += @size[y]

      @rank[x] += 1 if @rank[x] == @rank[y]
    end
  end

  def same?(x, y)
    find(x) == find(y)
  end

  def size(x)
    @size[find(x)]
  end
end

N, Q = gets.split.map(&:to_i)
P = gets.split.map(&:to_i)
uf = UnionFind.new(N + 1)

P.each.with_index(1) do |v, i|
  next if v == -1

  uf.unite(v, i)
end

Q.times do
  a, b = gets.split.map(&:to_i)

  if uf.same?(a, b)
    puts 'Yes'
  else
    puts 'No'
  end
end
0