結果

問題 No.1390 Get together
ユーザー simansiman
提出日時 2021-02-16 04:20:26
言語 Ruby
(3.3.0)
結果
AC  
実行時間 761 ms / 2,000 ms
コード長 945 bytes
コンパイル時間 434 ms
コンパイル使用メモリ 11,500 KB
実行使用メモリ 45,000 KB
最終ジャッジ日時 2023-10-01 01:45:40
合計ジャッジ時間 15,659 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 84 ms
15,156 KB
testcase_01 AC 82 ms
15,248 KB
testcase_02 AC 83 ms
15,388 KB
testcase_03 AC 93 ms
15,644 KB
testcase_04 AC 92 ms
15,344 KB
testcase_05 AC 92 ms
15,740 KB
testcase_06 AC 91 ms
15,504 KB
testcase_07 AC 91 ms
15,592 KB
testcase_08 AC 92 ms
15,476 KB
testcase_09 AC 95 ms
15,660 KB
testcase_10 AC 82 ms
15,336 KB
testcase_11 AC 82 ms
15,244 KB
testcase_12 AC 83 ms
15,040 KB
testcase_13 AC 82 ms
15,296 KB
testcase_14 AC 82 ms
15,248 KB
testcase_15 AC 83 ms
15,256 KB
testcase_16 AC 642 ms
33,872 KB
testcase_17 AC 676 ms
43,960 KB
testcase_18 AC 674 ms
33,864 KB
testcase_19 AC 761 ms
44,804 KB
testcase_20 AC 738 ms
43,776 KB
testcase_21 AC 736 ms
44,872 KB
testcase_22 AC 713 ms
41,168 KB
testcase_23 AC 707 ms
41,292 KB
testcase_24 AC 725 ms
41,148 KB
testcase_25 AC 735 ms
43,724 KB
testcase_26 AC 738 ms
43,912 KB
testcase_27 AC 761 ms
43,544 KB
testcase_28 AC 755 ms
43,648 KB
testcase_29 AC 751 ms
43,672 KB
testcase_30 AC 742 ms
45,000 KB
testcase_31 AC 736 ms
43,804 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)
Q = N.times.map { gets.split.map(&:to_i) }
C = Hash.new { |h, k| h[k] = [] }

Q.each do |b, c|
  C[c] << b
end

ans = 0
uf = UnionFind.new(M + 1)

C.each do |c, pos_list|
  pos_list.each_cons(2) do |a, b|
    next if uf.same?(a, b)

    ans += 1
    uf.unite(a, b)
  end
end

puts ans
0