結果
| 問題 |
No.1054 Union add query
|
| コンテスト | |
| ユーザー |
siman
|
| 提出日時 | 2022-04-06 05:52:25 |
| 言語 | Ruby (3.4.1) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 1,007 bytes |
| コンパイル時間 | 46 ms |
| コンパイル使用メモリ | 7,424 KB |
| 実行使用メモリ | 27,904 KB |
| 最終ジャッジ日時 | 2024-11-27 16:50:27 |
| 合計ジャッジ時間 | 11,142 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 5 WA * 3 |
コンパイルメッセージ
Syntax OK
ソースコード
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
siman