結果

問題 No.1390 Get together
ユーザー yuruhiya
提出日時 2021-02-12 22:43:48
言語 Crystal
(1.14.0)
結果
AC  
実行時間 154 ms / 2,000 ms
コード長 930 bytes
コンパイル時間 14,169 ms
コンパイル使用メモリ 295,992 KB
実行使用メモリ 36,480 KB
最終ジャッジ日時 2024-07-19 23:39:29
合計ジャッジ時間 18,251 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 29
権限があれば一括ダウンロードができます

ソースコード

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