main = -> { n, m = read_line.split.map &.to_i64 c = read_line.split.map &.to_i64.pred sizes = c.tally graph = Array.new(n) { |color| Array(Array(Int64)).new(sizes[color]? || 0) { [] of Int64 } } hash = Array.new(n) { Hash(Int64, Int32).new } m.times do u, v = read_line.split.map &.to_i64.pred if 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] << v2 graph[color][v2] << u2 end end ans = n.times.sum { |color| sz = sizes.fetch(color, 0_i64) next 0_i64 if sz == 0 ut = NgLib::DisjointSet.new(sz) graph[color].each_with_index do |edges, u| edges.each do |v| ut.unite(u, v) end end (0...sz).count { |i| ut.leader(i) == i }.to_i64 - 1 } puts ans } main.call module NgLib class DisjointSet @n : Int32 @parent_or_size : Array(Int32) def initialize @n = 0 @parent_or_size = Array(Int32).new end def initialize(size : Int) @n = size.to_i32 @parent_or_size = [-1] * size end def unite(a : Int, b : Int) : Int32 x = leader(a) y = leader(b) return x if x == y if -@parent_or_size[x] < -@parent_or_size[y] x, y = y, x end @parent_or_size[x] += @parent_or_size[y] @parent_or_size[y] = x x end def equiv?(a : Int, b : Int) : Bool leader(a) == leader(b) end def leader(a : Int) : Int32 return a.to_i32 if @parent_or_size[a] < 0 @parent_or_size[a] = leader(@parent_or_size[a]) @parent_or_size[a] end def size(a : Int) : Int32 -@parent_or_size[leader(a)] end def groups : Array(Array(Int32)) | Nil leader_buf = [0] * @n group_size = [0] * @n @n.times do |i| leader_buf[i] = leader(i) group_size[leader_buf[i]] += 1 end res = Array.new(@n){ [] of Int32 } @n.times do |i| res[leader_buf[i]] << i end res.delete([] of Int32) res end end end