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?

問題概要

N個の入力が与えられ、それぞれの入力はsweetまたはsaltyである。
sweetが2回連続で与えられるとそれ以降の入力が受け取れなくなる。最後まで入力を受け取ることはできるか。

解法と実装

sweetを連続して入力として受け取った回数をcntでカウントしています。
for文で順番に見ることで、カウントすることができます。

N = int(input())
cnt = 0
for i in range(N-1): # N-1番目、すなわち一番最後まで見ている時は含まない
  S = input() # for文ごとに文字列をダウンロードする
  if S == "sweet": # 入力がsweetだったらcntを増やす
    cnt += 1
  else:
    cnt = 0 # 入力がsaltyだったらカウントをリセット
  if cnt == 2:
    break
if cnt == 2: # 最終的にcntが2だったら最後まで食べていない
  print("No")
else:
  print("Yes")

rangeをNにすると、少し実装がややこしくなります。

N = int(input())
cnt = 0
for i in range(N): # rangeをNにするなら
  if i == N-1: # 最後にsweetが連続する場合を排除する必要がある
    cnt = 0
  S = input()
  if S == "sweet":
    cnt += 1
  else:
    cnt = 0
  if cnt == 2:
    break
if cnt == 2:
  print("No")
else:
  print("Yes")

リストとして入力を持つこともできます。

N = int(input()) # 個数を入力として受け取る
A = [] # 空の配列を用意する
for i in range(N):
  S = input() # 入力を受け取る
  A.append(S) # 入力を配列に追加
  
ans = True # 最後まで食べられるかどうか
for i in range(N-2): # i+1番目まで調べる かつ 最後の2回で連続していても問題ないので、rangeはN-2
  if A[i] == "sweet" and A[i+1] == "sweet": # 2回連続でsweetの時、最後まで食べられない
    ans = False
    
if ans:
  print("Yes")
else:
  print("No")

備考

最後の2回でsweetが連続していたとしても、最後まで入力が受け取れているので、回答としてはYesになります。気をつけてください。
私はこの記事の執筆中にそれで間違えました。
WA++;

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?