LoginSignup
0
0

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

Last updated at Posted at 2023-05-20

はじめに

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

A - A to Z String 2

a-257.rb
n, x = gets.split.map(&:to_i)
puts (65 + ((x - 1) / n)).chr

解説

N個ずつ並べるので、Aから見て(x - 1)をnで割った位置にある文字が答えとなります。

B - 1D Pawn

b-257.rb
n, k, q = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
l = gets.split.map(&:to_i)

q.times do |i|
  index = l[i] - 1
  next if a[index] == n
  if l[i] == k
    a[index] += 1
  elsif a[index] + 1 < a[l[i]]
    a[index] += 1
  end
end
puts a.join(" ")

解説

(公式解説を参考にしました)

以下の場合分けをすることにより実装することができます。
1.Li=Kならば(K=Nの場合は除く)、K<NよりA[L[i]-1]の値をインクリメントします。
2.上記以外でかつ、次のマスにコマがなければA[L[i]-1]の値をインクリメントします。

C - Robot Takahashi

c-257.rb
# 修正前
n = gets.to_i
s = gets.chomp
w = gets.split.map(&:to_i)

array = []
w.each_with_index do |factor, index|
  array << [factor, s[index]]
end
array.sort!

ans = count = s.count("1")
array.each_with_index do |factor, index|
  if factor[1] == "1"
    count -= 1
  else
    count += 1
  end
  
  if index != n - 1
    ans = [ans, count].max if factor[0] != array[index + 1][0]
  else
    ans = [ans, count].max
  end
end
puts ans
c-257.rb
# 修正後
n = gets.to_i
s = gets.chomp
w = gets.split.map(&:to_i)

array = w.zip(s.chars).sort

ans = count = s.count("1")
array.each_with_index do |(weight, child_or_adult), index|
  count += (child_or_adult == "1") ? -1 : 1
- ans = [ans, count].max if array.dig(index + 1) && weight != array[index + 1][0]
+ ans = [ans, count].max if array.dig(index + 1, 0) != weight 
end
puts [ans, count].max

解説

公式解説を参考にしました)

与えられた体重を昇順にソートし、1番左から線を引き右にずらしていくことで判定していきます(線の左が子ども、右が大人)。countの初期値については、最初すべての人が大人と判定してるため大人の数が正しく判定できる人数になります。

0
0
3

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