結果
問題 | No.2563 色ごとのグループ |
ユーザー |
|
提出日時 | 2023-12-02 15:35:29 |
言語 | Crystal (1.14.0) |
結果 |
AC
|
実行時間 | 385 ms / 2,000 ms |
コード長 | 2,167 bytes |
コンパイル時間 | 15,782 ms |
コンパイル使用メモリ | 297,740 KB |
実行使用メモリ | 79,488 KB |
最終ジャッジ日時 | 2024-09-26 18:57:39 |
合計ジャッジ時間 | 19,968 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 35 |
ソースコード
main = -> {n, m = read_line.split.map &.to_i64c = read_line.split.map &.to_i64.predsizes = c.tallygraph = Array.new(n) { |color| Array(Array(Int64)).new(sizes[color]? || 0) { [] of Int64 } }hash = Array.new(n) { Hash(Int64, Int32).new }m.times dou, v = read_line.split.map &.to_i64.predif c[u] == c[v]color = c[u]hash[color][u] = hash[color].size unless hash[color].has_key?(u)hash[color][v] = hash[color].size unless hash[color].has_key?(v)u2 = hash[color][u]v2 = hash[color][v]graph[color][u2] << v2graph[color][v2] << u2endendans = n.times.sum { |color|next 0_i64 if sizes.fetch(color, 0_i64) == 0ut = NgLib::DisjointSet.new(sizes.fetch(color, 0_i64))graph[color].each_with_index do |edges, u|edges.each do |v|ut.unite(u, v)endendut.groups.size - 1}puts ans}main.callmodule NgLibclass DisjointSet@n : Int32@parent_or_size : Array(Int32)def initialize@n = 0@parent_or_size = Array(Int32).newenddef initialize(size : Int)@n = size.to_i32@parent_or_size = [-1] * sizeenddef unite(a : Int, b : Int) : Int32x = leader(a)y = leader(b)return x if x == yif -@parent_or_size[x] < -@parent_or_size[y]x, y = y, xend@parent_or_size[x] += @parent_or_size[y]@parent_or_size[y] = xxenddef equiv?(a : Int, b : Int) : Boolleader(a) == leader(b)enddef leader(a : Int) : Int32return a.to_i32 if @parent_or_size[a] < 0@parent_or_size[a] = leader(@parent_or_size[a])@parent_or_size[a]enddef size(a : Int) : Int32-@parent_or_size[leader(a)]enddef groups : Array(Array(Int32)) | Nilleader_buf = [0] * @ngroup_size = [0] * @n@n.times do |i|leader_buf[i] = leader(i)group_size[leader_buf[i]] += 1endres = Array.new(@n){ [] of Int32 }@n.times do |i|res[leader_buf[i]] << iendres.delete([] of Int32)resendendend