0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

RubyでAtCoder ABC261(A, B, C)を解いてみた

Last updated at Posted at 2023-05-11

はじめに

Webエンジニアを目指して、RubyやRailsをいじってます。
今回は、RubyでAtCoder ABC261のA, B, Cを解きました。備忘録として解き方をまとめていきたいと思います。

A - Intersection

a-261.rb
l1, r1, l2, r2 = gets.split.map(&:to_i)
if l1 > l2
  l1, r1, l2, r2 = l2, r2, l1, r1
end
puts r1 <= l2 ? 0 : r1 <= r2 ? r1 - l2 : r2 - l2

解説

最初にl1, l2の大小関係により1と2を入れ替えることで、条件分岐の数を減らしています。

B - Tournament Result

b-261.rb
# 修正前
n = gets.to_i
array = Array.new(n){ gets.chomp }

n.times do |i|
  n.times do |j|
    if array[i][j] == "W"
      if array[j][i] != "L"
        puts "incorrect"
        exit
      end
    elsif array[i][j] == "L"
      if array[j][i] != "W"
        puts "incorrect"
        exit
      end
    elsif array[i][j] == "D"
      if array[j][i] != "D"
        puts "incorrect"
        exit
      end
    end
  end
end
puts "correct"
b-265.rb
# 修正後
n = gets.to_i
array = Array.new(n){ gets.chomp.chars.map{ |c| c == "W" ? 1 : c == "L" ? -1 : 0} }

n.times do |i|
  array[i].each_with_index do |c, j|
    next if j <= i
    if c != -array[j][i]
      puts "incorrect"
      exit
    end
  end
end
puts "correct"

解説

Nが1000以下と小さいので2重ループを回して、incorrectとなる場合があるかどうかを全探索することができます。

C - NewFolder(1)

c-261.rb
n = gets.to_i
count = Hash.new(0)
n.times do
    s = gets.chomp
    puts count[s] == 0 ? s : s + "(#{count[s]})"
    count[s] += 1
end

解説

連想配列hashを使って、それまでに同じ文字列がいくつあったのかを記録することで実装することができます。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?