0
0

More than 1 year has passed since last update.

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

Last updated at Posted at 2023-05-23

はじめに

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

A - 2^N

a-256.rb
puts 2 ** gets.to_i

B - Batters

b-256.rb
# 修正前
n = gets.to_i
a = gets.split.map(&:to_i)
ans = 0
array = Array.new(4, 0)
n.times do |i|
  array[0] = 1
  4.downto(0) do |j|
    if array[j] == 1
      if j + a[i] >= 4
        ans += 1
        array[j] = 0
      else
        array[j], array[j + a[i]] = 0, 1
      end
    end
  end
end
puts ans
b-256.rb
n = gets.to_i
a = gets.split.map(&:to_i)[-3..]

array = []
a.each do |hit|
  array.concat ([1] + [0] * (hit - 1))
end
puts n - array[-3..].sum

解説

問題文の通りに条件分岐を行うことで実装することができます。

C - Filling 3x3 array

c-256.rb
h1, h2, h3, w1, w2, w3 = gets.split.map(&:to_i)
ans = 0
- for a in 1..28
+ for a in 1..(h1 - 2)
-   for b in 1..28
+   for b in 1..(h1 - a - 1)
      c = h1 - a - b
-     for d in 1..28
+     for d in 1..(h2 - 2)
-       for e in 1..28
+       for e in 1..(h2 - d - 1)
        f = h2 - d - e

        i = w3 - c - f
        g = w1 - a - d
        h = w2 - b - e
        next if i != h3 - g - h

-       ans += 1 if [c, f, i, g, h].min > 0
+       ans += 1 if [i, g, h].min > 0
      end
    end
  end
end
puts ans

解説

3×3のマスに入る数字を[[a, b, c][d, e, f][g, h, i]]とします。そして、行・列それぞれの場合において和が一致していればansの値をインクリメントします。

D - Union of Interval

d-256.rb
n = gets.to_i
array = Array.new(n){ gets.split.map(&:to_i) }.sort

log_status = [array[0]]
array.each_with_index do |(left, right), index|
  next if index == 0
  pre_left, pre_right = log_status[-1]
- if pre_left <= left && left <= pre_right
+ if left <= pre_right
    log_status[-1][1] = right if pre_right < right
  else
    log_status << [left, right]
  end
end

log_status.each do |answer|
  puts answer.join(" ")
end
別解
n = gets.to_i
array = Array.new(n){ gets.split.map(&:to_i) }.sort

right = 0
array.chunk_while do |(_, pre_right), (left, _)|
  right = [right, pre_right].max
  left <= right
end.each do |section|
  puts "#{section[0][0]} #{section.sort_by{ |i, j| -j }[0][-1]}"
end

解説

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

与えられた配列を左側が昇順(同じ場合は右側も昇順)になるようにソートしておきます。そして、log_status配列を用意しておき、次の区間の左側が前の区間内にあり、かつ次の区間の右側が前の区間の右側よりも大きければ右側の値を更新します。それ以外はそのままlog_status配列に記録します。最後に、空白区切りでlog_status配列の要素を出力すればOKです。

0
0
6

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