1
1

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 3 years have passed since last update.

しゃくとり法ではqueueを使おう委員会(Ruby編)

Posted at

はじめに

@hibit さんの記事、しゃくとり法ではqueueを使おう委員会(C++編) の二番煎じです。

ABC 032 C - 列

n, k = gets.split.map(&:to_i)
s = n.times.map{ gets.to_i }
if s.include?(0)
  puts n
  exit
end
t = 1
max = 0
q = []
s.each do |x|
  q << x
  t *= x
  while t > k && q.size > 0
    t /= q.shift
  end
  max = q.size if max < q.size
end
puts max

しゃくとり法でqueueを使用しますと、ソースコードが2/3になります。
短ければ短いほど、早解きやバグり難さで有利となります。

q = []
q << x  # 入れる
q.shift # 出す

入れて出すだけで、煩わしい添え字の処理が不要になります。

ABC 038 C - 単調増加

gets
a = gets.split.map(&:to_i)
q = []
q << a.shift
cnt = 1
a.each do |x|
  if q[-1] < x
    q << x
    cnt += q.size
  else
    q.clear
    q << x
    cnt += 1
  end
end
puts cnt
q = []
q << x
q.clear

この問題では、shiftの代わりにclearを用いて、それまでのデータを一気に消去しています。

ARC 022 B - 細長いお菓子

n = gets.to_i
a = gets.split.map(&:to_i)
q = []
h = Hash.new(0)
max = 0
a.each do |x|
  q << x
  h[x] += 1
  while h[x] > 1
    h[q.shift] -= 1
  end
  max = q.size if max < q.size
end
puts max
  while h[x] > 1
    h[q.shift] -= 1
  end

この問題では、queuehashを組み合わせて使用してます。

まとめ

  • ABC 032 C を解いた
  • ABC 038 C を解いた
  • ARC 022 B を解いた
  • hibit さんありがとう
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?