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

Posted at

はじめに

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

A - You should output ARC, though this is ABC.

a-255.rb
r, c = gets.split.map(&:to_i)
a, b = gets.split.map(&:to_i)
d, e = gets.split.map(&:to_i)

if r == 1
  puts c == 1 ? a : b
else
  puts c == 1 ? d : e
end

B - Light It Up

b-255.rb
n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
array = Array.new(n) { gets.split.map(&:to_i) }

ans = 0
array.each_with_index do |(x, y), index|
  next if a.include?(index + 1)
  d = a.map{ |nx| (x - array[nx - 1][0]) ** 2 + (y - array[nx - 1][1]) ** 2 }.min
  ans = [ans, d].max
end
puts Math.sqrt(ans)

解説

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

その人から最も近い人が明かりをもっていれば良いので、答えはその人から最も近い人までの距離の最大値となります。

C - ±1 Operation 1

c-255.rb
def f(a, d, i)
  a + i * d
end

x, a, d, n = gets.split.map(&:to_i)

if d < 0
  a += d * (n - 1)
  d *= -1
end

if x <= a
  puts a - x
  exit
elsif x >= f(a, d, n - 1)
  puts x - f(a, d, n - 1)
  exit
end

result = (0..n - 1).bsearch { |i| f(a, d, i) >= x }
ans = [(f(a, d, result) - x).abs, (f(a, d, result - 1) - x).abs].min
puts ans

解説

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

最初に、D<0の場合は与えられた等差数列を反転します。このとき答えは、Xに最も近いSの要素を二分探索して求めた値とXとの差となります。

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?