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 ABC267(A, B, C)を解いてみた

Last updated at Posted at 2023-05-05

はじめに

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

A - Saturday

a-267.rb
array = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
puts 5 - array.index(gets.chomp)

解説

基準が土曜日なので5からインデックスを引いています。

B - Split?

b-267.rb
# 修正前
s = gets.chomp
if s[0] == "1"
  puts "No"
else
  col3 = s[1] == "0" && s[7] == "0" ? "0" : "1"
  col4 = s[4] == "0" ? "0" : "1"
  col5 = s[2] == "0" && s[8] == "0" ? "0" : "1"
  s = s[6] + s[3] + col3 + col4 + col5 + s[5] + s[9]
  4.times do |i|
    for j in i + 2..6
      t = s[i..j]
      if t[0] == "1" && t[-1] == "1"
        if t[1..-2].include?("0")
          puts "Yes"
          exit
        end
      end
    end
  end
  puts "No"
end
b-267.rb
# 修正後
s = gets.chomp
if s[0] == "1" || s == "0" * 10
  puts "No"
else
  cols = Array.new(7, false)
  [3, 2, 4, 1, 3, 5, 0, 2, 4, 6].each_with_index do |col_index, i|
    cols[col_index] = true if s[i] == "1"
  end

  left = cols.index(true) + 1
  right = cols.rindex(true) - 1
  if cols[left..right].include?(false)
    puts "Yes"
  else
    puts "No"
  end
end

解説

最初にそれぞれの列に対してピンが1つでも倒れているか調査し、sを置き換えています。そして、ピンが少なくとも1つ倒れている異なる2つのピンに対してその間の列にピンがすべて倒れている列があればYesを出力して終了、最後までスプリットがなければNoを出力します。

C - Index × A(Continuous ver.)

c-267.rb
n, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b, sum = 0, 0
m.times do |i|
  b += a[i] * (i + 1)
  sum += a[i]
end

ans = b
(n - m).times do |i|
  b = b - sum + (m * a[i + m])
  sum = sum - a[i] + a[i + m]
  ans = [ans, b].max
end
puts ans

解説

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

\sum_{i=1}^{m}i×A_i-\sum_{i=1}^{m}i×A_{i+1}=\sum_{i=1}^{m}A_i-M×A_{M+1}

であることを利用しています。

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?