AtCoder Beginner Contest C - Connect Cities Difficulty: 363
This theme, Union Find
Recently, there was Similar problem and AtCoder Library Practice Contest. However, the ash rate is amazing. By the way, last time it was Difficulty: 676 </ font>. Ruby
ruby.rb
class UnionFind
def initialize(n)
@parents = Array.new(n, -1)
end
def find(x)
@parents[x] < 0 ? x : @parents[x] = find(@parents[x])
end
def parents
@parents
end
def union(x, y)
x = find(x)
y = find(y)
return if x == y
if @parents[x] > @parents[y]
x, y = y, x
end
@parents[x] += @parents[y]
@parents[y] = x
end
end
n, m = gets.split.map(&:to_i)
u = UnionFind.new(n)
m.times do
a, b = gets.split.map(&:to_i)
u.union(a - 1, b - 1)
end
puts u.parents.select{ _1 < 0 }.size - 1
sub.rb
puts u.parents.select{ _1 < 0 }.size - 1 #this time
puts -u.parents.min #Last time
Just change the last line of Last time --Qiita to ʻAC`.
sub.rb
@parents = [-3, 0, -2, 2, 0]
Explaining in the previous input example 1
, in ʻu.parents, ʻu.parents [0]
and ʻu.parents [2]` can be divided into two representative groups. It's OK if you connect it with one road.
There is also a move to create a Ruby version of ACL on here --github.
It's attention required
.
Ruby | |
---|---|
Code length(Byte) | 567 |
Execution time(ms) | 170 |
memory(KB) | 15612 |
Referenced site
Recommended Posts