Problem:


Score : 400 points

Problem Statement

Snuke has N strings. The i-th string is s_i.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4



Sample input:
3
ABCA
XBAZ
BAD


Sample output:
2

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for _ in range(N)]
B_A = 0
notB_A = 0
B_notA = 0
ans = 0
for s in S:
    if s[0] == "B" and s[-1] == "A":
        B_A += 1
    elif s[0] == "B":
        B_notA += 1
    elif s[-1] == "A":
        notB_A += 1
    for i in range(len(s) - 1):
        if s[i : i + 2] == "AB":
            ans += 1

if B_A:
    ans += B_A - 1
    if notB_A > 0:
        ans += 1
        notB_A -= 1
    if B_notA > 0:
        ans += 1
        B_notA -= 1

print(ans + min(notB_A, B_notA))

Submission status: Accepted

Solution code:
def solve():
    N = int(input())
    a = 0
    b = 0
    ab = 0
    ans = 0
    for _ in range(N):
        s = input()
        if s[-1] == 'A' and s[0] == 'B':
            ab += 1
        elif s[-1] == 'A':
            a += 1
        elif s[0] == 'B':
            b += 1
        ans += s.count('AB')
        
    if ab == 0:
        ans += min(a, b)
    else:
        if a == 0 and b == 0:
            ans += ab - 1
        else:
            ans += ab + min(a, b)
            
    return ans
    
print(solve())

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import deque, Counter
from heapq import heappop, heappush
from bisect import bisect_right

def main():
    N = int(input())
    s = [input() for _ in range(N)]
    a = 0
    b = 0
    c = 0#a&b
    ans = 0
    for i in range(N):
        if s[i][0] == 'B':
            if s[i][-1] == 'A':
                c += 1
            else:
                b += 1
        elif s[i][-1] == 'A':
            a += 1
        ans += s[i].count('AB')
      
    if a+b>0:
        print(ans + (c-1) + min(a+1,b+1))
    else:
        print(ans + max(0,c-1))
    # print(a,b,c)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())
# N, K = [int(i) for i in input().split()]
countA = 0
countB = 0
countAB = 0
countBA = 0
for i in range(N):
    s = input()
    countAB += s.count('AB')
    if s[0] == 'B':
        countB += 1
    if s[-1] == 'A':
        countA += 1
    if s[0] == 'B' and s[-1] == 'A':
        countBA += 1
if countA != 0 and countA == countBA and countB == countBA:
    print(countAB + countBA - 1)
else:
    print(countAB + min(countA, countB))

Submission status: Accepted

Solution code:
import sys
n = int(input())
ans, c, h, t = 0, 0, 0, 0

for x in sys.stdin.readlines():
    x = x.rstrip()
    ans += x.count("AB")
    if x[-1] == "A" and x[0] == "B":
        c += 1
    elif x[-1] == "A":
        t += 1
    elif x[0] == "B":
        h += 1
if t + h > 0:
    ans += min(t, h) + c
elif c > 0:
    ans += c-1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = list(input() for _ in range(n))
cou = 0
for i in s:
    cou += i.count('AB')
a = 0
b = 0
both = 0
for i in s:
    if i[0]=="B":
        b += 1
    if i[-1]=="A":
        a += 1
    if i[0]=="B" and i[-1]=="A":
        both += 1
if min(a,b)==both and a==b:
    print(cou+max(min(a,b)-1,0))
else:
    print(cou+min(a,b))

Submission status: Accepted

Solution code:
#import sys
#import numpy as np
#import math
#import itertools
#from fractions import Fraction
#import itertools
from collections import deque
#import heapq
#from fractions  import gcd
#input=sys.stdin.readline
#import bisect

n=int(input())
s=[input() for _ in range(n)]
ans=0
bn=an=0
d=0
for i in range(n):
    ans+=s[i].count("AB")
    if s[i][0]=="B":
        an+=1
        if s[i][-1]=="A":
            d+=1
    if s[i][-1]=="A":
        bn+=1
if an==0 or bn==0:
  print(ans)
  exit()
if bn==an==d:
    print(ans+d-1)
else:
    print(ans+min(an,bn))

Submission status: Accepted

Solution code:
import sys
N = int(sys.stdin.readline().rstrip())

ans = 0
cnt_start_b = 0
cnt_end_a = 0
cnt_start_b_end_a = 0

for _ in range(N):
    s = sys.stdin.readline().rstrip()
    ans += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        cnt_start_b_end_a += 1
    elif s[0] == "B":
        cnt_start_b += 1
    elif s[-1] == "A":
        cnt_end_a += 1

if cnt_start_b_end_a > 0:
    if cnt_end_a == cnt_start_b == 0:
        ans += cnt_start_b_end_a - 1
    elif cnt_end_a == 0:
        ans += cnt_start_b_end_a
    elif cnt_start_b == 0:
        ans += cnt_start_b_end_a
    else:
        ans += cnt_start_b_end_a + 1 + min(cnt_end_a - 1, cnt_start_b - 1)
else:
    ans += min(cnt_end_a, cnt_start_b)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
a, b, ab = 0, 0, 0
for _ in range(n):
    s = list(input())
    l = len(s)
    for i in range(l - 1):
        if s[i] == "A" and s[i + 1] == "B":
            ans += 1
    if s[0] == "B":
        b += 1
    if s[l - 1] == "A":
        a += 1
    if s[0] == "B" and s[l - 1] == "A":
        ab += 1
if a == b == ab:
    a -= 1
ans += min(n - 1, max(0, min(a, b)))
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
s = [input() for _ in range(N)]
t = sum([s[i].count("AB") for i in range(N)])

p = sum([1 if s[i][-1] == "A" else 0 for i in range(N)])
q = sum([1 if s[i][0] == "B" else 0 for i in range(N)])
r = sum([1 if s[i][0] == "B" and s[i][-1] == "A" else 0 for i in range(N)])

p -= r
q -= r

ans=t
#print(t)
#print(p,q,r)

if r==0:
  ans += min(p,q)
else:
  ans += r-1
  if p>=1:
    p = p-1
    ans +=1
  if q>=1:
    q = q-1
    ans +=1
  ans += min(p,q)
print(ans)

Submission status: Accepted

Solution code:
# (1)ABが含まれる個数・・・まず単純にカウント
# (2)Aで終わるけどBで始まらないものの個数
# (3)Bで始まるものAで終わらないもののの個数
# (4)Bで始まってAで終わるものの個数 の個数 - 1
# (4)が1以上ある場合、(2),(3)を一つずつ使うことでそれぞれ+1
# それでも(2)(3)のペアが作れればペアごとに+1

import sys
readline = sys.stdin.readline

N = int(readline())
ans = 0
a_end = 0
b_start = 0
a_end_b_start = 0

for i in range(N):
  s = readline().rstrip()
  ans += s.count("AB")
  if s[-1] == "A" and s[0] == "B":
    a_end_b_start += 1
  elif s[-1] == "A":
    a_end += 1
  elif s[0] == "B":
    b_start += 1

if a_end_b_start > 0:
  ans += a_end_b_start - 1
  if a_end > 0:
    a_end -= 1
    ans += 1
  if b_start > 0:
    b_start -= 1
    ans += 1

ans += min(a_end,b_start)
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと


def read_a_int(): return int(read())


def read_ints(): return list(map(int, read().split()))


def read_col(H):
    '''H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_tuple(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


def read_matrix(H):
    '''H is number of rows'''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right

# https://atcoder.jp/contests/diverta2019/tasks/diverta2019_c

# B*A,*A,B*,*の4つに分類される。
# *に関しては事前に全部カウントしておけば良い
# B*A同士で作ったほうが有利(個数-1増える)
# *A,B*は 少ない方の個数増える
# 後者2つはコーナーケースに注意(つまり、B*Aがデータセットにある場合はさらに+1できる)(消化しきれない場合)

N = int(input())
base = 0
b_ = 0
_a = 0
b_a = 0
for _ in range(N):
    s = read()[:-1]
    if s.startswith('B') and s.endswith('A'):
        b_a += 1
    elif s.startswith('B'):
        b_ += 1
    elif s.endswith('A'):
        _a += 1
    base += s.count('AB')

ans = base
if b_a:
    ans += b_a - 1

if b_ and b_a:
    ans += 1
    b_ -= 1  # b_aの端に結合

if _a and b_a:
    ans += 1
    _a -= 1  # b_aの端に結合

ans += min(b_, _a)
print(ans)


# print(base + b_a + min(b_, _a) + (-1 if b_ == _a and b_a > 0 else 0))
# バグってる
# ちゃんとやるか
# print(base, b_a, b_, _a)

Submission status: Accepted

Solution code:
n = int(input())
S = [input() for i in range(n)]

ans = 0
a_cnt = 0
b_cnt = 0
ba_cnt = 0
for i in range(n):
    ans+=S[i].count('AB')
    if S[i][0]=='B' and S[i][-1]=='A':
        ba_cnt+=1
    elif S[i][-1]=='A':
        a_cnt+=1
    elif S[i][0]=='B':
        b_cnt+=1

print(ans+min(a_cnt,b_cnt)+ba_cnt-1*(ba_cnt>0 and a_cnt==b_cnt==0))

Submission status: Accepted

Solution code:
from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations # (string,3) 3回
from collections import deque
from collections import defaultdict
import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
def readInts():
  return list(map(int,input().split()))
def I():
  return int(input())
n = I()
B = 0
A = 0
ans = 0
BA = 0
for i in range(n):
    s = input()
    ans += s.count('AB')
    if len(s)!=1:
        if s[0] == 'B' and s[-1] == 'A':
            BA += 1
        elif s[0] == 'B':
            B += 1
        elif s[-1] == 'A':
            A += 1
print(ans + BA + min(A,B) if A!= 0 or B!=0 else ans + max(0,BA-1))

Submission status: Accepted

Solution code:
N = int(input())
A = 0#末尾がA
B = 0#先頭がB
BA = 0#先頭がB かつ 末尾がA
AB = 0#ABの数

for i in range(N):
    s = input()
    AB += s.count("AB")
    if s[0] == "B":
        B += 1
    if s[-1] == "A":
        A += 1
    if s[0] == "B" and s[-1] == "A":
        BA += 1
        B -= 1
        A -= 1
ans = 0
ans += AB

if min(A,B) > 0:
    ans += BA + 1
    A -= 1
    B -= 1
    ans += min(A,B)
else:
    ans += max(BA + min(1, max(A,B)) -1,0)
print(ans)
    
#if BA > max(A,B) - min(A,B):
#    ans += (BA - (max(A,B) - min(A,B))) / 2
#print(A,B,BA,AB)

Submission status: Accepted

Solution code:
n,*a=open(0).read().split()
ba=xa=bx=ans=0
for i in a:
    if i[0]=="B" and i[-1]=="A":
        ba+=1
    elif i[0]=="B":
        bx+=1
    elif i[-1]=="A":
        xa+=1
    ans+=i.count("AB")    
print(ans+min(xa,bx)+ba-1*(ba>0 and xa==bx==0))

Submission status: Accepted

Solution code:
n = int(input())
s = []
last_a = 0
first_b = 0
cnt = 0
both = 0
for i in range(n):
    ss = input()
    s.append(ss)
    if ss[0] == 'B':
        first_b += 1
    if ss[-1] == 'A':
        last_a += 1
    if ss[0] == 'B' and ss[-1] == 'A':
        both += 1
        last_a -= 1
        first_b -= 1

    for j in range(len(ss)-1):
        if ss[j] == 'A' and ss[j+1] == 'B':
            cnt += 1

sub = abs(first_b - last_a)
sub2 = both - sub
ans = cnt
if both == 0:
    ans += min(first_b,last_a)
elif first_b == last_a == 0:
    ans += max(0,both - 1)
else:
    ans += min(first_b,last_a) + min(sub,both) + max(0,sub2)

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
cnt_ba = 0
cnt_a = 0
cnt_b = 0
for _ in range(n):
    s = str(input())
    ans += s.count('AB')
    if s[-1] == 'A' and s[0] == 'B':
        cnt_ba += 1
    elif s[-1] == 'A':
        cnt_a += 1
    elif s[0] == 'B':
        cnt_b += 1
if n >= 2:
    if cnt_a == cnt_b == 0:
        ans += max(0, cnt_ba - 1)
    else:
        ans += min(cnt_a, cnt_b) + cnt_ba
print(ans)

Submission status: Accepted

Solution code:
import sys
def Z(): return int(input())
def ZZ(): return [int(_) for _ in input().split()]

def main():
    N = Z()
    output = 0
    x = y = z = 0
    for _ in range(N):
        s = sys.stdin.readline().rstrip()
        output += s.count('AB')
        if s[0] == 'B' and s[-1] == 'A': y += 1
        elif s[-1] == 'A': x += 1
        elif s[0] == 'B': z += 1
        
    if y == 0:
        output += min(x, z)
        print(output)
        return

    if x > 0:
        output += y + min(1, z) + max(min(x-1, z-1), 0)
        print(output)
        return

    output += y - 1 + min(1, z)
    print(output)

    return

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
s = [input() for i in range(n)]
a = 0
b = 0
c = 0
cnt = 0
for i in s:
    cnt += i.count("AB")
    if i[0] == "B" and i[-1] == "A":
        a += 1
    elif i[0] == "B":
        b += 1
    elif i[-1] == "A":
        c += 1
if a == 0:
    print(min(b, c) + cnt)
else:
    if b + c == 0:
        print(cnt + a - 1)
    else:
        print(cnt + a + min(b, c))

Submission status: Accepted

Solution code:
n = int(input())
res = 0
numa = numb = numboth = 0
for _ in range(n):
    s = input()
    res += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        numboth += 1
    elif s[0] == "B":
        numb += 1
    elif s[-1] == "A":
        numa += 1

#print(numboth, numa, numb)
#print(res)

if numboth == 0:
    res += min(numa, numb)
else:
    if numa == 0 and numb == 0:
        res += numboth - 1
    else:
        res += numboth
        res += min(numa, numb)
print(res)

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
a = 0
b = 0
ba = 0
for i in range(n):
    s = input()
    ans += s.count("AB")
    if s[0] == "B":
        if s[-1] == "A":
            ba += 1
        else:
            b += 1
    elif s[-1] == "A":
        a += 1
if a >= 1 or b >= 1:
    print(ans+ba+min(a,b))
else:
    print(ans+max(0,ba-1))

Submission status: Accepted

Solution code:
n = int(input())
slist = []
ans = 0
startB, endA = 0, 0
b_a = 0
for _ in range(n):
    s = list(input())
    for j in range(len(s) - 1):
        if ("".join(s[j:j + 2]) == "AB"):
            ans += 1
    startB += 1 if s[0] == "B" else 0
    endA += 1 if s[len(s) - 1] == "A" else 0
    b_a += 1 if s[0] == "B" and s[len(s) - 1] == "A" else 0

if startB == b_a and endA == b_a:
    startB -= 1

print(ans+min(max(0, startB), max(0, endA)))

Submission status: Accepted

Solution code:
N=int(input())
b,ba,a=0,0,0
ans=0
for i in range(N):
    s=input()
    for i in range(len(s)-1):
        if s[i:i+2]=='AB':
            ans+=1
    if s[0]=='B' and s[-1]=='A':
        ba+=1
    elif s[-1]=='A':
        a+=1
    elif s[0]=='B':
        b+=1
if b==0 and a==0:
    print(ans+max(ba-1,0))
else:
    print(ans+ba+min(a,b))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
t = open(0).read()
c1 = c2 = c3 = 0
for s in t.split():
    if s[-1] == "A" and s[0] == "B":
        c1 += 1
    elif s[-1] == "A":
        c2 += 1
    elif s[0] == "B":
        c3 += 1
if c1:
    a = c1 + min(c2, c3) if c2 + c3 > 0 else c1 - 1
else:
    a = min(c2, c3)

print(t.count("AB") + a)

Submission status: Accepted

Solution code:
n = int(input())
s = []
for i in range(n):
    s.append(input())

cnt_end_a = 0
cnt_bgn_b = 0
cnt_end_a_bgn_b = 0

ans = 0
for i in range(n):
    if s[i][0] == 'B':
        if s[i][len(s[i])-1] == 'A':
            cnt_end_a_bgn_b += 1
        else:
            cnt_bgn_b += 1
    elif s[i][len(s[i])-1] == 'A':
        cnt_end_a += 1
    for j in range(len(s[i])-1):
        if s[i][j] == 'A' and s[i][j+1] == 'B':
            ans += 1

#print(cnt_end_a, cnt_bgn_b, cnt_end_a_bgn_b)

if cnt_end_a_bgn_b == 0:
    ans += min(cnt_bgn_b, cnt_end_a)
elif cnt_end_a == 0 and cnt_bgn_b == 0:
    ans += cnt_end_a_bgn_b - 1
elif cnt_end_a == 0:
    ans += cnt_end_a_bgn_b
elif cnt_bgn_b == 0:
    ans += cnt_end_a_bgn_b
else:
    ans += cnt_end_a_bgn_b + min(max(cnt_bgn_b, cnt_end_a), min(cnt_bgn_b, cnt_end_a))
print(ans)

Submission status: Accepted

Solution code:
n = int(input())

ans = 0
last_a = 0
first_b = 0
cnt = 0

for i in range(n):
    s = input()
    ans += s.count("AB")
    if s[-1] == "A":
        last_a += 1
    if s[0] == "B":
        first_b += 1
    if s[-1] == "A" and s[0] == "B":
        cnt += 1

if last_a == first_b & cnt > 0:
    ans += min(last_a, first_b) - 1
else:
    ans += min(last_a, first_b)

print(ans)

Submission status: Accepted

Solution code:
def solve():
    N = int(input())
    s = []
    ans = 0

    A_cnt = 0
    B_cnt = 0
    BA_cnt = 0
    for i in range(N):
        s_tmp = input()
        s.append(s)
        for j in range(len(s_tmp)-1):
            if s_tmp[j] == "A" and s_tmp[j+1] == "B":
                ans += 1
        
        if s_tmp[0] == "B" and s_tmp[-1] == "A":
            BA_cnt += 1
        elif s_tmp[0] == "B":
            B_cnt += 1
        elif s_tmp[-1] == "A":
            A_cnt += 1
    
    if BA_cnt > 0:
        ans += BA_cnt - 1
        if A_cnt > 0:
            A_cnt -= 1
            ans += 1
        if B_cnt > 0:
            B_cnt -= 1
            ans += 1
    
    ans += min(A_cnt,B_cnt)
    
    print(ans)
if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()

from collections import defaultdict, deque, Counter
from sys import exit
import heapq
import math
from fractions import gcd
import copy
from itertools import permutations
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

from itertools import permutations
from math import factorial, hypot

#############
# Main Code #
#############

N = getN()
cnt = 0
last_a = 0
first_b = 0
double = 0
for i in range(N):
    s = input()
    for j in range(len(s) - 1):
        if s[j] == 'A' and s[j + 1] == 'B':
            cnt += 1
    if s[0] == 'B' and s[-1] == 'A':
        double += 1
    elif s[0] == 'B':
        first_b += 1
    elif s[-1] == 'A':
        last_a += 1
opt = 0
if first_b == 0 and last_a == 0 and double != 0:
    opt = double - 1
else:
    opt = min(first_b + double, last_a + double)
print(cnt + opt)

Submission status: Accepted

Solution code:
N = int(input())
ba, bc, ca = 0, 0, 0
c = 0
for _ in range(N):
    ss = input()
    if ss[0] == 'B':
        if ss[-1] =='A':
            ba += 1
        else: bc += 1
    else:
        if ss[-1] == 'A':
            ca += 1
    c += ss.count('AB')

cnt = max(ba - 1, 0)
if ba >= 1:
    if ca >= 1:
        ca -= 1
        cnt += 1
    if bc >= 1:
        bc -= 1
        cnt += 1
cnt += min(ca, bc)

print(cnt + c)

Submission status: Accepted

Solution code:
N = int(input())

ab = 0
x = 0
y = 0
z = 0

for _ in range(N):
    s = input()
    ab += s.count("AB")
    if (s[-1] == "A" and s[0] == "B"):
        z += 1
    elif (s[-1] == "A"):
        x += 1
    elif (s[0] == "B"):
        y += 1

if (not x and not y) and z:
    print(ab + z-1)
else:
    print(ab + min(x+z, y+z))

Submission status: Accepted

Solution code:
N=int(input())
S=[]
cnt=Alist=Blist=0
key=False
for i in range(N):
    s=input()
    cnt+=s.count("AB")
    S=list(s)
    if S[0] == "B":
        Blist+=1
    if S[-1] == "A":
        Alist+=1
    if (S[0] == "B" and S[-1] != "A") or (S[0] != "B" and S[-1] == "A"):
        key = True

cnt += min(Alist,Blist)
if key or min(Alist,Blist)==0:
    print(cnt)
else:
    print(cnt-1)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6) #再帰関数の上限
import math
from copy import copy, deepcopy
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque 
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする


def input(): return sys.stdin.readline()[:-1]
def printl(li): print(*li, sep="\n")
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N=len(v)
    size=len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def main():
    mod = 10**9+7
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    N = int(input())
    #N, K = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    count=0

    ab=0
    a=0
    b=0
    for i in range(N):
        s=input()
        ls=len(s)
        for j in range(ls-1):
            if s[j:j+2]=='AB':
                count+=1
        if s[0]=='B' and s[-1]=='A':
            ab+=1
        elif s[-1]=='A':
            a+=1
        elif s[0]=='B':
            b+=1
    if a==0 and b==0:
        print(count+max(ab-1,0))
        exit()
    ans=min(a,b)+count
    ret=abs(a-b)
    if ret<=ab:
        ans+=ab
    else:
        ans+=ab
    print(ans)
    

    


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())

cntab = 0
cns = 0
cne = 0
cnse = 0
for _ in range(N):
    S = input()
    if S[0] == 'B' and S[-1] == 'A':
        cnse += 1
    elif S[0] == 'B':
        cns += 1
    elif S[-1] == 'A':
        cne += 1
    for s1, s2 in zip(S, S[1:]):
        if (s1 == 'A') and (s2 == 'B'):
            cntab += 1


if N == cnse:
    print(cntab + N - 1)
elif cnse == 0:
    print(cntab + min(cns, cne))
else:
    if (cns == 0) and (cne == 0):
        print(cntab + cnse - 1)
    elif (cns == 0) or (cne == 0):
        print(cntab + cnse)
    else:
        print(cntab + cnse + 1 + min(cns-1, cne-1))

Submission status: Accepted

Solution code:
n = int(input())
a = 0
b = 0
c = 0
ans = 0
for _ in range(n):
    s = input()
    if s[0]=='B' and s[-1]=='A':
        c+=1
    elif s[0]=='B':
        b+=1
    elif s[-1]=='A':
        a+=1
    
    for i in range(len(s)-1):
        if s[i:i+2] == 'AB':
            ans += 1
if c>0:
    ans += c-1
    if b>0:a += 1
    if a>0:b += 1

ans += min(a,b)
print(ans)

Submission status: Accepted

Solution code:
n=int(input())

headB=0
tailA=0
middleAB=0
ck=0
for _ in range(n):
    s=list(input())

    for i in range(1,len(s)):
        if s[i-1]=="A" and s[i]=="B":
            middleAB+=1
    if s[0]=="B":
        headB+=1
    if s[-1]=="A":
        tailA+=1
    if s[0]=="B" and s[-1]=="A":
        ck+=1

#BA
#BC
#CA みたいなケースは2になる

#BA
#BA　みたいなケースは１になる

if ck>0 and ck==tailA and ck==headB:
    print(middleAB+min(headB,tailA)-1)
else:
    print(middleAB+min(headB,tailA))

Submission status: Accepted

Solution code:
n = int(input())

a_end = 0
b_start = 0
a_b = 0
cnt = 0

for _ in range(n):
    s = input()
    cnt += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        a_b += 1
        continue
    if s[0] == "B":
        b_start += 1
    if s[-1] == "A":
        a_end += 1

if a_end == 0 and b_start == 0:
    tmp = max(a_b - 1, 0)
else:
    tmp = min(a_end,  b_start) + a_b
print(cnt + tmp)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


def main():
    N = int(input())
    S = [input().strip() for _ in range(N)]
    a = 0
    b = 0
    ba = 0
    za = 0

    ans = 0
    for s in S:
        if ba == 0 and s[0] == 'B' and s[-1] == 'A':
            ba = 1
        if za == 0 and s[0] != 'B' and s[-1] == 'A':
            za = 1

        ans += s.count("AB")

        if s[-1] == 'A':
            a += 1
        if s[0] == 'B':
            b += 1

    if ba == 1 and za == 0:
        print(ans + min(max(a, b) - 1, min(a, b)))
    else:
        print(ans + min(a, b))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N=int(input())
l=[input() for i in range(N)]
a_c=0
b_c=0
ab_c=0
ans=0
for i in l:
   ans+=i.count("AB")
   if i[0] == "B" and i[-1] == "A":
      ab_c+=1
      continue
   if i[-1] == "A":
      a_c+=1
   if i[0] == "B":
      b_c+=1
ans+=max(ab_c-1,0)
if a_c > 0 and ab_c>0:
   a_c-=1
   ans+=1
if b_c > 0 and ab_c>0:
   b_c-=1
   ans+=1
ans+=min(a_c,b_c)
print(ans)

Submission status: Accepted

Solution code:
def cal_single(S,N):
    output = 0
    for i in range(N):
        output += S[i].count("AB")
    return output

def cal_cont(S,N):
    a,b,ab = 0,0,0
    for i in range(N):
        if S[i][0] == "B" and S[i][-1] == "A":
            ab += 1
        elif S[i][0] == "B":
            b += 1
        elif S[i][-1] == "A":
            a += 1

    if ab == 0:
        return min(a,b)
    elif a + b == 0:
        return ab-1
    else:
        return ab + min(a,b)

def main():
    N = int(input())
    S = [input() for _ in range(N)]

    ans = cal_single(S,N)+cal_cont(S,N)

    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())

type1 = type2 = type3 = 0

ans = 0
while n > 0:
    s = input()
    ans += s.count("AB")

    if s[0] == "B" and s[-1] == "A":
        type3 += 1
    elif s[-1] == "A":
        type1 += 1
    elif s[0] == "B":
        type2 += 1

    n -= 1

ans += min(type1, type2)

if type3 > 0:
    if type1 == type2 == 0:
        ans += type3 - 1
    else:
        ans += type3

print(ans)

Submission status: Accepted

Solution code:
import sys

# import re
import math
import collections
# import decimal
import bisect
# import itertools
import fractions
# import functools
import copy
import heapq
import decimal
# import statistics
import queue

sys.setrecursionlimit(10000001)
INF = 10 ** 16
MOD = 10 ** 9 + 7

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))


# ===CODE===


def main():
    n = ni()
    b_start = 0
    a_end = 0
    b_and_a = 0
    ans = 0

    for _ in range(n):
        s = input()
        ans += s.count("AB")
        flgB = s[0] == "B"
        flgA = s[-1] == "A"
        if flgB and flgA:
            b_and_a += 1
        elif flgB:
            b_start += 1
        elif flgA:
            a_end += 1

    remain_a = max(0, a_end - b_and_a)
    remain_b = max(0, b_start - b_and_a)
    remain_ab_a = max(0, b_and_a - b_start)
    remain_ab_b = max(0, b_and_a - a_end)

    ans += min(b_start, b_and_a)
    ans += min(a_end, b_and_a)
    ans += min(remain_a, remain_b)

    if remain_ab_a == remain_ab_b == b_and_a:
        if min(remain_ab_a, remain_ab_b) > 0:
            ans += min(remain_ab_a, remain_ab_b) - 1
    else:
        ans += min(remain_ab_a, remain_ab_b)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from collections import deque


def read():
    N = int(input().strip())
    S = []
    for i in range(N):
        s = input().strip()
        S.append(s)
    return N, S


def solve(N, S):
    count = 0
    for s in S:
        for j in range(len(s)):
            if s[j:j+2] == "AB":
                count += 1
    head_b = []
    tail_a = []
    for i, s in enumerate(S):
        if s[0] == "B":
            head_b.append(i)
        if s[-1] == "A":
            tail_a.append(i)
    head_b = list(sorted(head_b))
    tail_a = list(sorted(tail_a))
    if len(head_b) == 0 or len(tail_a) == 0:
        return count
    # is_same?
    if len(head_b) == len(tail_a):
        is_same = True
        for b, a in zip(head_b, tail_a):
            if b != a:
                is_same = False
                break
        if is_same:
            count -= 1
    return count + min(len(head_b), len(tail_a))


if __name__ == '__main__':
    inputs = read()
    print(solve(*inputs))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
from math import sqrt
# def input(): return sys.stdin.readline()[:-1] # warning not \n
# def input(): return sys.stdin.buffer.readline()[:-1]

# n = int(input())



def solve():
    n = int(input())
    ans = 0
    a = 0
    b = 0
    c = 0
    for _ in range(n):
        s = input()
        a += s[-1] == 'A' and s[0] != 'B'
        b += s[0] == 'B' and s[-1] != 'A'
        c += s[0] == 'B' and s[-1] == 'A'
        ans += s.replace('AB', "*").count('*')
    if (a+b) > 0:
        print(ans + c + min(a, b))
    else:
        if c:
            c -= 1
        print(ans + c)
    

t = 1
# t = int(input())
for case in range(1,t+1):
    ans = solve()




"""




"""

Submission status: Accepted

Solution code:
n,*s=open(0).read().split()
a=0;b=0;ba=0;ans=0
for s_i in s:
  b+=(s_i[0]=='B')*(not s_i[-1]=='A')
  a+=(not s_i[0]=='B')*(s_i[-1]=='A')
  ba+=(s_i[0]=='B')*(s_i[-1]=='A')
  ans+=s_i.count('AB')
print(ans+ba+min(a,b)-(ba>0)*(a+b==0))

Submission status: Accepted

Solution code:
n = int(input())
s = [input() for i in range(n)]
 
ab = 0
a = 0
b = 0
 
d = 0
for i in s:
	d += i.count('AB')
	if i[0] == 'B' and i[-1] == 'A':
		ab += 1
	elif i[-1] == 'A':
		a += 1
	elif i[0] == 'B':
		b += 1
 
if ab == 0:
	d += min(a,b)
elif a+b == 0:
	d += ab-1
else:
	d += ab+min(a,b)
print (d)

Submission status: Accepted

Solution code:
n = int(input())

ans = 0
cntA = 0
cntB = 0
cntBA = 0
for i in range(n):
    s = input()
    ans += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        cntBA += 1
    elif s[-1] == 'A':
        cntA += 1
    elif s[0] == 'B':
        cntB += 1
if cntBA == 0:
    ans += min(cntA, cntB)
elif cntA + cntB == 0:
    ans += cntBA - 1
else:
    ans += cntBA + min(cntA, cntB)

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = [input() for i in range(n)]

ab = 0
a = 0
b = 0

d = 0
for i in s:
	d += i.count('AB')
	if i[0] == 'B' and i[-1] == 'A':
		ab += 1
	elif i[-1] == 'A':
		a += 1
	elif i[0] == 'B':
		b += 1

if ab == 0:
	d += min(a,b)
elif a+b == 0:
	d += ab-1
else:
	d += ab+min(a,b)
print (d)

Submission status: Accepted

Solution code:
N = int(input())
s = [input() for i in range(N)]

cnt = 0
ab_cnt = 0
b_cnt = 0
a_cnt = 0
for word in s:
    cnt += word.count('AB')
    l = word[0]
    r = word[-1]
    if l == 'B' and r == 'A':
        ab_cnt += 1
    elif l == 'B':
        b_cnt += 1
    elif r == 'A':
        a_cnt += 1

if ab_cnt == 0:
    ans = min(b_cnt, a_cnt)
elif a_cnt + b_cnt > 0:
    ans = ab_cnt + min(b_cnt, a_cnt)
else:
    ans = ab_cnt - 1

print(cnt + ans)