Last active
October 11, 2017 02:24
-
-
Save whatalnk/5545cab2dc134a28b774e909ffb9fdd5 to your computer and use it in GitHub Desktop.
AtCoder ARC #032 B - 道路工事
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
n, m = gets.chomp.split(" ").map(&:to_i) | |
node = Struct.new("Node", :to) | |
field = Array.new(n+1){node.new([])} | |
m.times do | |
a, b = gets.chomp.split(" ").map(&:to_i) | |
field[a].to << b | |
field[b].to << a | |
end | |
# Union Find | |
@par = (0..n).to_a | |
@rank = Array.new(n+1, 0) | |
def find(x) | |
if @par[x] == x | |
return x | |
else | |
@par[x] = find(@par[x]) | |
return @par[x] | |
end | |
end | |
def unite(x, y) | |
x = find(x) | |
y = find(y) | |
if x == y | |
return | |
end | |
if @rank[x] < @rank[y] | |
@par[x] = y | |
else | |
@par[y] = x | |
if @rank[x] == @rank[y] | |
@rank[x] += 1 | |
end | |
end | |
end | |
def same(x, y) | |
return find(x) == find(y) | |
end | |
(1..n).each do |i| | |
field[i].to.each do |j| | |
unite(i, j) | |
end | |
end | |
ans = 0 | |
(1..n).each do |i| | |
if @par[i] == i | |
ans += 1 | |
end | |
end | |
puts ans - 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment