結果

問題 No.2418 情報通だよ!Nafmoくん
ユーザー simansiman
提出日時 2023-08-18 13:57:34
言語 Ruby
(3.3.0)
結果
AC  
実行時間 364 ms / 2,000 ms
コード長 886 bytes
コンパイル時間 69 ms
コンパイル使用メモリ 7,296 KB
実行使用メモリ 27,136 KB
最終ジャッジ日時 2024-05-05 19:09:09
合計ジャッジ時間 7,148 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 88 ms
12,160 KB
testcase_01 AC 88 ms
12,288 KB
testcase_02 AC 88 ms
12,288 KB
testcase_03 AC 364 ms
23,168 KB
testcase_04 AC 192 ms
24,960 KB
testcase_05 AC 243 ms
14,592 KB
testcase_06 AC 287 ms
22,912 KB
testcase_07 AC 249 ms
13,952 KB
testcase_08 AC 310 ms
27,136 KB
testcase_09 AC 300 ms
15,488 KB
testcase_10 AC 356 ms
22,400 KB
testcase_11 AC 321 ms
22,016 KB
testcase_12 AC 256 ms
20,352 KB
testcase_13 AC 160 ms
14,464 KB
testcase_14 AC 234 ms
17,536 KB
testcase_15 AC 212 ms
12,416 KB
testcase_16 AC 350 ms
17,920 KB
testcase_17 AC 153 ms
12,544 KB
testcase_18 AC 251 ms
21,248 KB
testcase_19 AC 172 ms
21,888 KB
testcase_20 AC 226 ms
12,544 KB
testcase_21 AC 179 ms
16,128 KB
testcase_22 AC 169 ms
12,928 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