提出 #13758236
ソースコード 拡げる
class UnionFind
def initialize(n); @data = Array.new(n,-1); end
def find(a); @data[a] < 0 ? a : @data[a] = find(@data[a]); end
def same?(a,b); find(a) == find(b); end
def size(a); -@data[find(a)]; end
def unite(a,b)
a = find(a); b = find(b)
return if a == b
a,b = b,a if @data[a] > @data[b]
@data[a] += @data[b]; @data[b] = a
end
end
# UnionFind.new(N) := 要素数Nで初期化
# Ai := i番目の要素
# find(i) := Aiが属するグループ
# same?(i,j) := Ai,Ajが同じグループに属する
# size(i) := Aiが属するグループの要素の数
# unite(i,j) := Ai,Ajを同じグループに統合する
n,m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).map{|v|v-1}
uf = UnionFind.new(n)
m.times do
x,y = gets.split.map(&:to_i)
x -= 1; y -= 1
uf.unite(x,y)
end
ans = 0
n.times do |i|
ans += 1 if uf.same?(a[i],i)
end
puts ans
提出情報
| 提出日時 | |
|---|---|
| 問題 | D - Equals |
| ユーザ | tamura2004 |
| 言語 | Ruby (2.3.3) |
| 得点 | 400 |
| コード長 | 915 Byte |
| 結果 | AC |
| 実行時間 | 291 ms |
| メモリ | 12292 KiB |
ジャッジ結果
| セット名 | Sample | All | ||||
|---|---|---|---|---|---|---|
| 得点 / 配点 | 0 / 0 | 400 / 400 | ||||
| 結果 |
|
|
| セット名 | テストケース |
|---|---|
| Sample | 0_000.txt, 0_001.txt, 0_002.txt, 0_003.txt |
| All | 0_000.txt, 0_001.txt, 0_002.txt, 0_003.txt, 1_004.txt, 1_005.txt, 1_006.txt, 1_007.txt, 1_008.txt, 1_009.txt, 1_010.txt, 1_011.txt, 1_012.txt, 1_013.txt, 1_014.txt, 1_015.txt, 1_016.txt, 1_017.txt, 1_018.txt, 1_019.txt, 1_020.txt, 1_021.txt, 1_022.txt |
| ケース名 | 結果 | 実行時間 | メモリ |
|---|---|---|---|
| 0_000.txt | AC | 7 ms | 1788 KiB |
| 0_001.txt | AC | 7 ms | 1788 KiB |
| 0_002.txt | AC | 7 ms | 1788 KiB |
| 0_003.txt | AC | 7 ms | 1788 KiB |
| 1_004.txt | AC | 172 ms | 1788 KiB |
| 1_005.txt | AC | 243 ms | 12292 KiB |
| 1_006.txt | AC | 291 ms | 12292 KiB |
| 1_007.txt | AC | 7 ms | 1788 KiB |
| 1_008.txt | AC | 7 ms | 1788 KiB |
| 1_009.txt | AC | 7 ms | 1788 KiB |
| 1_010.txt | AC | 6 ms | 1788 KiB |
| 1_011.txt | AC | 7 ms | 1788 KiB |
| 1_012.txt | AC | 7 ms | 1788 KiB |
| 1_013.txt | AC | 9 ms | 1788 KiB |
| 1_014.txt | AC | 16 ms | 1788 KiB |
| 1_015.txt | AC | 7 ms | 1788 KiB |
| 1_016.txt | AC | 7 ms | 1788 KiB |
| 1_017.txt | AC | 10 ms | 1788 KiB |
| 1_018.txt | AC | 157 ms | 1788 KiB |
| 1_019.txt | AC | 74 ms | 9732 KiB |
| 1_020.txt | AC | 70 ms | 9732 KiB |
| 1_021.txt | AC | 72 ms | 9860 KiB |
| 1_022.txt | AC | 278 ms | 12292 KiB |