AtCoder上にある問題のうち、AtCoder Problemsでdiff 800以上と判定されているものを順番に解いていく企画。
基本的な考え方は全てコード中のコメントに入れてあるので、参照のこと。
出典:
diverta 2019 Programming Contest C – AB Substrings
実は何回か間違えながら、場合分けの鬼と化して解いてしまったのだが、最終的にはやることは同じだとしても、もう少しマシな書き方があるとは思う。とはいえ、可能な限り分かりやすく書くなら、こんな感じなのかもしれない。どっちやねん。
def main():
N = int(input())
strings = [input() for _ in range(N)]
cnt_a = 0
cnt_b = 0
cnt_ba = 0
result = 0
for s in strings:
result += s.count('AB')
if s[0] == 'B' and s[-1] == 'A':
cnt_ba += 1
elif s[0] == 'B':
cnt_b += 1
elif s[-1] == 'A':
cnt_a += 1
if cnt_ba > 0:
if cnt_a == 0 and cnt_b == 0:
result += cnt_ba - 1
elif cnt_a == 0 or cnt_b == 0:
result += cnt_ba
else:
result += cnt_ba + 1 + min(cnt_a - 1, cnt_b - 1)
else:
result += min(cnt_a, cnt_b)
print(result)
main()
関連