結果

問題 No.1054 Union add query
ユーザー simansiman
提出日時 2022-04-06 05:52:25
言語 Ruby
(3.3.0)
結果
WA  
実行時間 -
コード長 1,007 bytes
コンパイル時間 67 ms
コンパイル使用メモリ 11,476 KB
実行使用メモリ 27,384 KB
最終ジャッジ日時 2023-08-18 11:53:55
合計ジャッジ時間 10,977 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 85 ms
15,320 KB
testcase_01 AC 82 ms
15,120 KB
testcase_02 AC 80 ms
15,136 KB
testcase_03 WA -
testcase_04 WA -
testcase_05 WA -
testcase_06 AC 1,177 ms
20,076 KB
testcase_07 AC 1,111 ms
20,328 KB
testcase_08 AC 1,092 ms
20,192 KB
testcase_09 AC 1,255 ms
27,192 KB
testcase_10 AC 913 ms
27,320 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

class UnionFind
  def initialize(n)
    @size = Array.new(n, 1)
    @b = 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 add(x, v)
    root = find(x)
    @b[root] += v
  end

  def get(x)
    if @parent[x] == x
      @b[x]
    else
      @b[x] + get(@parent[x])
    end
  end

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

    if @size[x] < @size[y]
      @parent[x] = y
      @size[y] += @size[x]
      @b[x] -= @b[y]
    else
      @parent[y] = x
      @size[x] += @size[y]
      @b[y] -= @b[x]
    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)
uf = UnionFind.new(N + 1)
A = Hash.new(0)

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

  case t
  when 1
    uf.unite(a, b)
  when 2
    uf.add(a, b)
  when 3
    puts uf.get(a)
  end
end
0