Solving with Ruby AtCoder ACL Beginner Contest C Union Find (DSU)

Introduction

This theme

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.

Ruby version of AtCoder Library (ACL)

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

Summary

  • Solved ACLBC C
  • Become familiar with Ruby

Referenced site

Recommended Posts

Solving with Ruby AtCoder ACL Beginner Contest C Union Find (DSU)
Solve with ac-library-rb AtCoder Union Find (DSU)
Solving with Ruby, Perl and Java AtCoder ABC 128 C
AtCoder Beginner Contest 170 A, B, C up to ruby
Solving with Ruby, Perl and Java AtCoder ABC 129 C (Part 1)
Learning Ruby with AtCoder 6 [Contest 168 Therefore]
AtCoder Beginner Contest 167 C Problem (Java)
Learning Ruby with AtCoder 7 [Contest 168 Triple Dots]
Solving with Ruby, Perl and Java AtCoder ABC 129 C (Part 2) Dynamic programming
AtCoder Beginner Contest 168
Solving with Ruby and Crystal AtCoder ABC 129 D
AtCoder Beginner Contest 182 Participation Article
AtCoder Beginner Contest 132 D Problem
Solving with Ruby, Perl and Java AtCoder ABC 136 D Breadth-first search
Solving with Ruby AtCoder 1st Algorithm Practical Test A Exception Handling
Solve AtCoder Beginner Contest 151 in java
Solve AtCoder Beginner Contest 150 in java
Solve AtCoder Beginner Contest 153 in java
Solve AtCoder Beginner Contest 175 in java
Solve AtCoder Beginner Contest 160 in java
Solve AtCoder Beginner Contest 152 in java
Solve AtCoder Beginner Contest 156 in java
[Beginner] Let's solve AtCoder problem with Ruby while looking at the article!