結果

問題 No.1390 Get together
ユーザー yuruhiyayuruhiya
提出日時 2021-02-12 22:43:48
言語 Crystal
(1.11.2)
結果
AC  
実行時間 186 ms / 2,000 ms
コード長 930 bytes
コンパイル時間 18,361 ms
コンパイル使用メモリ 258,008 KB
実行使用メモリ 34,860 KB
最終ジャッジ日時 2023-09-27 05:35:18
合計ジャッジ時間 23,020 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,388 KB
testcase_01 AC 2 ms
4,436 KB
testcase_02 AC 3 ms
4,416 KB
testcase_03 AC 5 ms
5,208 KB
testcase_04 AC 5 ms
5,164 KB
testcase_05 AC 5 ms
5,056 KB
testcase_06 AC 5 ms
5,176 KB
testcase_07 AC 4 ms
5,140 KB
testcase_08 AC 4 ms
5,156 KB
testcase_09 AC 6 ms
5,464 KB
testcase_10 AC 3 ms
4,396 KB
testcase_11 AC 3 ms
4,484 KB
testcase_12 AC 3 ms
4,380 KB
testcase_13 AC 3 ms
4,416 KB
testcase_14 AC 2 ms
4,436 KB
testcase_15 AC 3 ms
4,416 KB
testcase_16 AC 132 ms
25,652 KB
testcase_17 AC 178 ms
31,788 KB
testcase_18 AC 135 ms
25,656 KB
testcase_19 AC 182 ms
31,160 KB
testcase_20 AC 185 ms
31,328 KB
testcase_21 AC 184 ms
31,344 KB
testcase_22 AC 161 ms
34,792 KB
testcase_23 AC 158 ms
34,860 KB
testcase_24 AC 158 ms
34,848 KB
testcase_25 AC 183 ms
30,748 KB
testcase_26 AC 183 ms
31,512 KB
testcase_27 AC 186 ms
30,744 KB
testcase_28 AC 185 ms
31,512 KB
testcase_29 AC 180 ms
30,824 KB
testcase_30 AC 178 ms
30,800 KB
testcase_31 AC 178 ms
30,628 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

lib C
  fun strtoll(s : UInt8*, p : UInt8**, b : Int32) : Int64
end

class String
  def to_i64
    C.strtoll(self, nil, 10)
  end
end

class UnionFind
  @d : Array(Int32)

  def initialize(n : Int32)
    @d = Array.new(n, -1)
  end

  def root(x : Int32)
    @d[x] < 0 ? x : (@d[x] = root(@d[x]))
  end

  def unite(x : Int32, y : Int32)
    x = root(x)
    y = root(y)
    return false if x == y
    x, y = y, x if @d[x] > @d[y]
    @d[x] += @d[y]
    @d[y] = x
    true
  end

  def same?(x : Int32, y : Int32)
    root(x) == root(y)
  end

  def size(x : Int32)
    -@d[root(x)]
  end

  def root?(x : Int32)
    @d[x] < 0
  end
end

n, m = read_line.split.map(&.to_i)
a = (0...n).map { [] of Int32 }
n.times do
  b, c = read_line.split.map(&.to_i.pred)
  a[c] << b
end
uf = UnionFind.new(m)
a.each do |b|
  b.sort.each_cons_pair { |i, j| uf.unite(i, j) }
end
puts (0...m).select { |i| uf.root?(i) }.sum { |i| uf.size(i) - 1 }
0