結果

問題 No.2418 情報通だよ!Nafmoくん
ユーザー simansiman
提出日時 2023-08-18 13:57:34
言語 Ruby
(3.3.0)
結果
AC  
実行時間 303 ms / 2,000 ms
コード長 886 bytes
コンパイル時間 276 ms
コンパイル使用メモリ 11,420 KB
実行使用メモリ 29,564 KB
最終ジャッジ日時 2023-08-18 13:57:43
合計ジャッジ時間 7,139 ms
ジャッジサーバーID
(参考情報)
judge15 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 68 ms
15,244 KB
testcase_01 AC 73 ms
15,236 KB
testcase_02 AC 70 ms
15,220 KB
testcase_03 AC 279 ms
24,628 KB
testcase_04 AC 147 ms
28,156 KB
testcase_05 AC 188 ms
17,876 KB
testcase_06 AC 258 ms
24,244 KB
testcase_07 AC 198 ms
16,996 KB
testcase_08 AC 254 ms
29,564 KB
testcase_09 AC 230 ms
18,596 KB
testcase_10 AC 273 ms
24,048 KB
testcase_11 AC 276 ms
23,880 KB
testcase_12 AC 216 ms
23,080 KB
testcase_13 AC 127 ms
17,316 KB
testcase_14 AC 179 ms
19,980 KB
testcase_15 AC 175 ms
15,532 KB
testcase_16 AC 303 ms
20,632 KB
testcase_17 AC 123 ms
15,448 KB
testcase_18 AC 199 ms
23,484 KB
testcase_19 AC 138 ms
23,284 KB
testcase_20 AC 192 ms
15,312 KB
testcase_21 AC 146 ms
19,192 KB
testcase_22 AC 135 ms
16,068 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, M = gets.split.map(&:to_i)
uf = UnionFind.new(2 * N + 1)

M.times do
  a, b = gets.split.map(&:to_i)
  uf.unite(a, b)
end

counter = Hash.new(0)

1.upto(2 * N) do |i|
  par = uf.find(i)
  counter[par] += 1
end

puts N - counter.map { |k, v| v / 2 }.sum
0