LoginSignup
0
0

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

Posted at

はじめに

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

A - Median?

a-253.rb
a = gets.split
puts a[1] == a.sort[1] ? "Yes" : "No"

B - Distance Between Tokens

b-253.rb
h, _ = gets.split

x = y = 0
h.to_i.times do |i|
  gets.chomp.chars.each_with_index do |char, j|
    if char == "o"
      y = i - y
      x = j - x
    end
  end
end
puts x.abs + y

C - Max - Min Query

c-253.rb
q = gets.to_i

hash = Hash.new(0)
max = -1
min = Float::INFINITY
q.times do
  t, x, c = gets.split.map(&:to_i)
  case t
  when 1
    hash[x] += 1
    max = [max, x].max
    min = [min, x].min
  when 2
    hash[x] = [0, hash[x] - c].max
    if hash[x] == 0
      hash.delete(x)
      if hash.empty?
        max = -1
        min = Float::INFINITY
      else
        max = hash.keys.max if max == x
        min = hash.keys.min if min == x
      end
    end
  when 3
    puts max - min if max != -1
  end
end

解説

集合に含まれる要素xの個数を連想配列hashに保持させます。

  1. t = 1のとき
    連想配列のxの値をインクリメントします。また、集合に含まれる最大値と最小値を更新します。
  2. t = 2のとき
    集合に含まれるxの個数がcよりも大きければ、xの値からcを引き、c以下であれば0とします。このとき、要素数が0なら連想配列からxを削除し、最大値と最小値を更新します。
  3. t = 3のとき
    連想配列が空でなければ、最大値から最小値を引いた値を出力します。

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