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

Posted at

はじめに

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

A - Edge Checker

a-240.rb
a, b = gets.split.map(&:to_i)
puts (a == 1 && b == 10) || b == a + 1 ? "Yes" : "No"

B - Count Distinct Integers

b-240.rb
gets.to_i
puts gets.split.uniq.size

C - Jumping Takahashi

c-240.rb
n, x = gets.split.map(&:to_i)
dp = Array.new(n + 1){ Array.new(x + 1, false) }
dp[0][0] = true

n.times do |i|
  a, b = gets.split.map(&:to_i)
  (x + 1).times do |j|
    if dp[i][j]
      dp[i + 1][j + a] = true if j + a <= x
      dp[i + 1][j + b] = true if j + b <= x
    end
  end
end
puts dp[n][x] ? "Yes" : "No"

解説

dp[i][j] := i回ジャンプした後に座標j(j <= x)に移動できるかとしたdpを使って解くことができます。

D - Strange Balls

d-240.rb
gets.to_i
a = gets.split.map(&:to_i)

ball_counter = [[1, 0]]
count = 0
a.each do
  count += 1
  if _1 == ball_counter[-1][0]
    ball_counter[-1][1] += 1
    if _1 == ball_counter[-1][1]
      count -= _1
      ball_counter.pop
    end
  else
    ball_counter << [_1, 1]
  end
  puts count
end

解説

(他の方の提出結果を参考にしました)

ball_counter配列を用意して要素を[x, y] := [今いるところのボールに書かれた数字, 同じ数字が連続した回数]のようにしておきます。後は、随時値を更新していき、同じ数字が連続した回数とボールに書かれた数字が一致している時はcountからその個数分引くことで答えを求めることができます。

0
0
0

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?