結果

問題 No.1059 素敵な集合
ユーザー simansiman
提出日時 2022-04-24 01:40:41
言語 Ruby
(3.3.0)
結果
AC  
実行時間 366 ms / 2,000 ms
コード長 1,002 bytes
コンパイル時間 646 ms
コンパイル使用メモリ 11,276 KB
実行使用メモリ 23,232 KB
最終ジャッジ日時 2023-09-07 17:00:10
合計ジャッジ時間 6,063 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 85 ms
15,132 KB
testcase_01 AC 202 ms
23,156 KB
testcase_02 AC 149 ms
18,772 KB
testcase_03 AC 82 ms
15,180 KB
testcase_04 AC 81 ms
15,172 KB
testcase_05 AC 81 ms
15,304 KB
testcase_06 AC 129 ms
17,276 KB
testcase_07 AC 128 ms
17,276 KB
testcase_08 AC 154 ms
18,424 KB
testcase_09 AC 98 ms
15,904 KB
testcase_10 AC 167 ms
18,520 KB
testcase_11 AC 132 ms
17,584 KB
testcase_12 AC 110 ms
16,932 KB
testcase_13 AC 191 ms
19,440 KB
testcase_14 AC 89 ms
15,516 KB
testcase_15 AC 277 ms
22,388 KB
testcase_16 AC 142 ms
17,992 KB
testcase_17 AC 143 ms
18,184 KB
testcase_18 AC 183 ms
23,048 KB
testcase_19 AC 366 ms
23,232 KB
testcase_20 AC 356 ms
23,100 KB
testcase_21 AC 297 ms
22,800 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

L, R = gets.split.map(&:to_i)

table = Array.new(2 * R + 1, 0)
uf = UnionFind.new(R + 1)
ans = 0

L.upto(R) do |x|
  next if table[x] != 0
  table[x] = 1

  (2 * x).step(R, x) do |i|
    uf.unite(x, i)
    table[i] = 2
  end
end

L.upto(R) do |x|
  next if table[x] != 1

  if uf.same?(x, x - 1)
    next
  else
    uf.unite(x, x - 1)
    ans += 1
  end
end

puts ans - 1
0