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

Solution (Python):
import sys
import math
import copy
import heapq
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
sys.setrecursionlimit(1000000)


input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = float("inf")
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)

def nck(n, k, kaijyo):
    return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD

def npk(n, k, kaijyo):
    if k == 0 or k == n:
        return n % MOD
    return (kaijyo[n] * divide(kaijyo[n-k])) % MOD

def fact_and_inv(SIZE):
    inv = [0] * SIZE  
    fac = [0] * SIZE  
    finv = [0] * SIZE  
    inv[1] = 1
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    for i in range(2, SIZE):
        inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD
        fac[i] = fac[i - 1] * i % MOD
        finv[i] = finv[i - 1] * inv[i] % MOD

    return fac, finv

def renritsu(A, Y):
    
    
    
    A = np.matrix(A)
    Y = np.matrix(Y)
    Y = np.reshape(Y, (-1, 1))
    X = np.linalg.solve(A, Y)

    
    return X.flatten().tolist()[0]

class TwoDimGrid:
    
    def __init__(self, h, w, wall="
        self.h = h
        self.w = w
        self.size = (h+2) * (w+2)
        self.wall = wall
        self.get_grid()
        

    def get_grid(self):
        grid = [self.wall * (self.w + 2)]
        for i in range(self.h):
            grid.append(self.wall + getS() + self.wall)

        grid.append(self.wall * (self.w + 2))
        self.grid = grid
    def init_cost(self):
        self.cost = [INF] * self.size

    def pos(self, x, y):
        
        return y * (self.w + 2) + x
    def getgrid(self, x, y):
        return self.grid[y][x]
    def get(self, x, y):
        return self.cost[self.pos(x, y)]
    def set(self, x, y, v):
        self.cost[self.pos(x, y)] = v
        return
    def show(self):
        for i in range(self.h+2):
            print(self.cost[(self.w + 2) * i:(self.w + 2) * (i+1)])
    def showsome(self, tgt):
        for t in tgt:
            print(t)
        return
    def showsomejoin(self, tgt):
        for t in tgt:
            print("".join(t))
        return

    def search(self):
        grid = self.grid
        move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        move_eight = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
        
        
        
        
        


def soinsu(n):
    ret = defaultdict(int)
    for i in range(2, int(math.sqrt(n) + 2)):
        if n % i == 0:
            while True:
                if n % i == 0:
                    ret[i] += 1
                    n //= i
                else:
                    break

    if not ret:
        return {n: 1}
    return ret


def solve():
    n = getN()
    ans, a, b = 0,0,0
    andb = 0
    for i in range(n):
        prev = ""
        S = getS()
        for c in S:
            if prev == "A" and c == "B":
                ans += 1

            prev = c
        if S.startswith("B"):
            b += 1
        if S.endswith("A"):
            a += 1
        if S.startswith("B") + S.endswith("A"):
            andb  += 1

    if a == b and b == andb and b > 0:
        b -= 1

    print(ans + min(a, b))



def main():
    n = getN()
    for _ in range(n):
        solve()

    return
if __name__ == "__main__":
    
    solve()

Solution (Python):
n = int(input())
cnt_a = cnt_b = cnt_ba = 0
ans = 0
for _ in range(n):
    s = input()
    ans += s.count('AB')
    if s[0] == 'B':
        cnt_b += 1
        if s[-1] == 'A':
            cnt_ba += 1
    if s[-1] == 'A':
        cnt_a += 1


if cnt_a == cnt_b == n:
    ans += n - 1
elif cnt_ba > 0 and cnt_a == cnt_b == cnt_ba:
    ans += cnt_ba - 1
else:
    ans += min(cnt_a, cnt_b)
print(ans)

Solution (Python):
N=int(input())

answer=0
num_ba=0
num_a=0
num_b=0
for _ in range(N):
  s=input()
  for i in range(1,len(s)):
    if s[i-1]=="A" and s[i]=="B":
      answer+=1
  
  if s[0]=="B" and s[-1]=="A":
    num_ba+=1
  elif s[0]=="B":
    num_b+=1
  elif s[-1]=="A":
    num_a+=1

if num_ba>0:
  answer+=num_ba-1
  if num_b>0:
    answer+=1
    num_b-=1
  if num_a>0:
    answer+=1
    num_a-=1
  
answer+=min(num_a,num_b)
print(answer)

Solution (Python):
a=b=c=ans=0
for _ in range(int(input())):
    s=input()
    ans+=s.count("AB")
    a+=s[-1]=="A"
    b+=s[0]=="B"
    c+=s[-1]+s[0]=="AB"
print(ans+min(a,b)-(0<a==b==c))

Solution (Python):
a = b = c = ans = 0
for _ in range(int(input())):
    s = input()
    ans += s.count("AB")
    a += s[-1] == "A"
    b += s[0] == "B"
    c += s[-1] + s[0] == "AB"
print(ans+min(a, b)-(0 < a == b == c))

Solution (Python):

n = int(input())
a = b = c = ans = 0
for _ in range(n):
    s = input()
    ans += s.count("AB")
    a += s[-1] == "A"
    b += s[0] == "B"
    c += s[-1] + s[0] == "AB"
print(ans + min(a, b) - (0 < a == b == c))

Solution (Python):
n = int(input())
internal_AB = 0
B_A = 0
B_ = 0
_A = 0
for i in range(n):
    s = input()
    for j in range(len(s)-1):
        if s[j] == 'A' and s[j+1] == 'B':
            internal_AB += 1
    if s[0] == 'B' and s[-1] == 'A':
        B_A += 1
    elif s[0] == 'B':
        B_ += 1
    elif s[-1] == 'A':
        _A += 1
if _A == 0 and B_ == 0:
    ans = max(0,B_A - 1)
elif _A == 0 or B_ == 0:
    ans = B_A
else:
    if B_A > 0:
        ans = B_A +1 + min(_A-1,B_-1)
    else:
        ans = min(B_,_A)
print(ans + internal_AB)

Solution (Python):
N = int(input())
ans,a,b,ab = 0,0,0,0

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

ans += ab + min(a,b)
if ab > 0 and a == b == 0:
    ans -= 1
print(ans)

Solution (Python):






N = int(input())
s = []
a = 0
b = 0
ab = 0
cnt = 0
for _ in range(N):
    tmp = input()
    cnt += tmp.count("AB")
    if tmp[0] == "B" and tmp[-1] == "A":
        ab += 1
    elif tmp[0] == "B":
        b += 1
    elif tmp[-1] == "A":
        a += 1
    s.append(tmp)





if ab==0:
    ans = cnt + min(a,b)
else:
    if a+b>0:
        ans = cnt + ab + min(a,b)
    else:
        ans = cnt + ab-1
print(ans)

Solution (Python):

import sys

sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read


sys.setrecursionlimit(10**7)







INF = 1 << 50



def run():
    N = int(input())
    S = [input() for _ in range(N)]
    countA = 0
    countB = 0
    countBA = 0
    countAB = 0
    for s in S:
        countAB += s.count('AB')
        
        if s[0] == 'B':
            if  s[-1] == 'A':
                countBA += 1
            else:
                countB += 1
        elif s[-1] == 'A':
            countA += 1

    
    if countBA > 1:
        countAB += countBA - 1
        countBA = 0

        if countA > 0:
            countAB += 1
            countA -= 1
        if countB>0:
            countAB += 1
            countB -= 1

    plus = min(countA, countB)

    countAB += plus
    countA -= plus
    countB -= plus

    plus = min(countBA, countA)
    countAB += plus
    countBA -= plus
    countA -= plus

    plus = min(countBA, countB)
    countAB += plus

    print(countAB)






if __name__ == "__main__":
    run()

Solution (Python):
def resolve():
    '''
    code here
    '''
    N = int(input())
    Ss = [input() for _ in range(N)]

    num_ab = 0
    num_a = 0
    num_b = 0
    num_b_a = 0

    for line in Ss:

        num_ab += line.count('AB')
        if line[0] == 'B' and line[-1] == 'A':
            num_b_a += 1
        elif line[-1] == 'A':
            num_a += 1
        elif line[0] == 'B':
            num_b += 1
        
    res = num_ab
    if num_b_a > 0:
        res += num_b_a -1

        if num_a > 0:
            res += 1
            num_a -= 1

        if num_b > 0:
            res += 1
            num_b -= 1

    res += min(num_a, num_b)
    print(res)


if __name__ == "__main__":
    resolve()

Solution (Python):
N = int(input())
ab, a, b, ans = 0, 0, 0, 0
for i in range(N):
  s = str(input())
  ans += s.count('AB')
  if (s[0]=='B') and (s[-1]=='A'):
    ab += 1
  elif s[0] == 'B':
    b += 1
  elif s[-1] == 'A':
    a += 1
    
if ab > 0:
  ans += ab - 1
  if a > 0:
    ans += 1
    a -= 1
  if b > 0:
    ans += 1
    b -= 1
ans += min(a, b)
print(ans)

Solution (Python):
n = int(input())
s = [input() for _ in range(n)]

cnt = 0
cnta = 0
cntb = 0
cntab = 0
for i in range(n):
    if 'AB' in s[i]:
        cnt += s[i].count('AB')
    if s[i][0] == 'B' and s[i][-1] == 'A':
        cntab += 1
    elif s[i][0] == 'B':
        cntb += 1
    elif s[i][-1] == 'A':
        cnta += 1
    
if cntab == 0:
    cnt += min(cnta, cntb)
else:
    if cnta + cntb > 0:
        cnt += cntab + min(cnta, cntb)
    else:
        cnt += cntab - 1
print(cnt)

Solution (Python):


import sys
 
sys.setrecursionlimit(10 ** 8)
ini = lambda: int(sys.stdin.readline())
inm = lambda: map(int, sys.stdin.readline().split())
inl = lambda: list(inm())
ins = lambda: sys.stdin.readline().rstrip()
debug = lambda *a, **kw: print("\033[33m", *a, "\033[0m", **dict(file=sys.stderr, **kw))

N = ini()
ans = 0
lastA = 0
firstB = 0
BA = 0

for i in range(N):
    s = input()
    
    for j in range(len(s)-1):
        if s[j:j+2] == "AB":
            ans += 1

    
    if s[0] == "B" and s[-1] == "A":
        BA += 1
    elif s[0] == "B":
        firstB += 1
    elif s[-1] == "A":
        lastA += 1

if BA >= 2:
    ans += BA - 1


if BA >= 1 and lastA >= 1 and firstB >=1:
    ans += 2 + min(lastA-1,firstB-1)

elif BA >= 1 and lastA >= 1 and firstB == 0:
    ans += 1

elif BA >= 1 and lastA == 0 and firstB >= 1:
    ans += 1

elif BA < 1 and lastA >= 1 and firstB >= 1:
    ans += min(lastA,firstB)

print(ans)

Solution (Python):
n = int(input())
ans = 0
ba = 0 
a = 0 
b = 0 
sss = []
for i in range(n):
    s = input()
    for j in range(len(s)-1):
        if s[j:j+2] == 'AB':
            ans+=1
    if s[0] == 'B' and s[-1] == 'A': ba += 1
    else:
        if s[0] == 'B': b+=1
        if s[-1] == 'A': a+=1
"""
貪欲で解けると思う
まずbaを並べて、可能な限りその先頭にa、末尾にbをつける
a,bが残るようであれば、ペアにする
"""
if ba > 0:
    ans += ba-1
    if a>0:
        ans+=1
        a-=1
    if b>0:
        ans+=1
        b-=1
ans += min(a, b)
print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 9)

def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')







def solve():
    N = II()
    A = []
    B = []
    BA = []
    cnt = 0
    for i in range(N):
        s = input()
        l = list(s)
        if l[0] == 'B' and l[-1] == 'A':
            BA.append(i)
        elif l[0] == 'B':
            B.append(i)
        elif l[-1] == 'A':
            A.append(i)
        cnt += s.count('AB')
    
    la = len(A)
    lb = len(B)
    lba = len(BA)

    if la > 0 and lb > 0:
        cnt += min(la, lb) + lba
    elif la == 0 and lb == 0:
        if lba > 1:
            cnt += lba - 1
    else:
        cnt += lba
    print(cnt)


if __name__ == '__main__':
    solve()

Solution (Python):
N = int(input())
both = 0 
cnt = 0
gA = 0
sB = 0
for _ in range(N):
    s = input()
    cnt += s.count('AB')
    if s[-1] == 'A': gA += 1
    if s[0] == 'B': sB += 1
    if s[0] == 'B' and s[-1] == 'A': both += 1
ans = min(gA, sB) + cnt
if both == gA and gA == sB and both != 0:
    ans -= 1
print(ans)

Solution (Python):
n = int(input())
a = 0
b = 0
c = 0
total = 0
for _ in range(n):
    s = input()
    total += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        c+=1
    elif s[-1] == 'A':
        a+=1
    elif s[0] == 'B':
        b+=1

if a+b == 0:
    print(total + max(0, c - 1))
else:
    print(total + min(a, b) + c)

Solution (Python):
n=int(input())
a=0
b=0
ab=0
num=0
for i in range(n):
    s=input()
    if s[0]=="B" and s[-1]=="A":
        ab+=1
    elif s[0]=="B":
        b+=1
    elif s[-1]=="A":
        a+=1
    for j in range(len(s)-1):
        if s[j]=="A" and s[j+1]=="B":
            num+=1
if a!=0 and b!=0:
    num+=ab+1
    a-=1
    b-=1
    num+=min(a,b)
elif a!=0:
    num+=ab
elif b!=0:
    num+=ab
else:
    num+=max(0,ab-1)
print(num)

Solution (Python):
import sys,math,collections,itertools
input = sys.stdin.readline

N = int(input())
lAend = 0
lBstart = 0
lAe_Bs = 0
cnt = 0

for i in range(N):
    S = input().rstrip()
    if S[0]=='B' and S[-1] =='A':
        lAe_Bs+=1
    elif S[0] == 'B':
        lBstart+=1
    elif S[-1] == 'A':
        lAend+=1
    cnt += S.count('AB')

if lAe_Bs >0:
    cnt += lAe_Bs -1
    
if lAe_Bs > 0 and lAend >0:
    cnt += 1
    lAend -=1
if lAe_Bs > 0 and lBstart>0:
    cnt +=1
    lBstart -=1

cnt += min(lAend,lBstart)

print(cnt)

Solution (Python):
import sys,math,collections,itertools
input = sys.stdin.readline

N = int(input())
Aend = []
Bstart = []
Ae_Bs = []
cnt = 0

for i in range(N):
    S = input().rstrip()
    if S[0]=='B' and S[-1] =='A':
        Ae_Bs.append(S)
    elif S[0] == 'B':
        Bstart.append(S)
    elif S[-1] == 'A':
        Aend.append(S)
    cnt += S.count('AB')

lAe_Bs = len(Ae_Bs)
lBstart = len(Bstart)
lAend = len(Aend)

if lAe_Bs >0:
    cnt += lAe_Bs -1
    
if lAe_Bs > 0 and lAend >0:
    cnt += 1
    lAend -=1
if lAe_Bs > 0 and lBstart>0:
    cnt +=1
    lBstart -=1

cnt += min(lAend,lBstart)

print(cnt)

Solution (Python):
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    N = I()
    s = [SS() for _ in range(N)]

    ans = sum([i.count('AB') for i in s])

    
    
    tA = 0
    fB = 0
    fBtA = 0
    for i in s:
        if i[-1] == 'A' and i[0] == 'B':
            fBtA += 1
        elif i[-1] == 'A':
            tA += 1
        elif i[0] == 'B':
            fB += 1

    if tA == fB == 0:
        ans += max(fBtA - 1, 0)
    else:
        ans += min(tA, fB) + fBtA

    print(ans)

if __name__ == '__main__':
    resolve()

Solution (Python):
n,*s=open(0).read().split()
w=''
b=[]
a=[]
e=""
for i in s:
    if i[-1]=='A' and i[0]=="B":
        w+=i
    elif i[-1]=='A':
        a.append(i)
    elif i[0]=='B':
        b.append(i)
    else:
        e+=i

a=iter(a)
b=iter(b)
if len(w)!=0:
    w=next(a,'')+w+next(b,'')
i,j=next(a,''),next(b,'')
while i!='' or j!='':
    w+=i+j
    i,j=next(a,''),next(b,'')
w+=e
print(w.count('AB'))

Solution (Python):
n = int(input())
s = [input() for _ in range(n)]
count = 0
a_count = 0
b_count = 0
ab_count = 0

for ss in s:
    count += ss.count("AB")
    if ss[0] == "B" and ss[-1] == "A":
        ab_count += 1
    elif ss[0] != "B" and ss[-1] == "A":
        a_count += 1
    elif ss[0] == "B" and ss[-1] != "A":
        b_count += 1

tmp_count = min(a_count,b_count)
if ab_count == 0:
    count += tmp_count
else:
    if a_count + b_count > 0:
        count += ab_count + tmp_count
    else:
        count += ab_count - 1
print(count)

Solution (Python):
def main():
    import sys

    def input(): return sys.stdin.readline().rstrip()

    n = int(input())
    s_table = [0]*3
    ans = 0
    for i in range(n):
        s = input()
        ans += s.count('AB')
        if s[0] == 'B' and s[-1] == 'A':
            s_table[0] += 1
        elif s[0] == 'B' and s[-1] != 'A':
            s_table[1] += 1
        elif s[0] != 'B' and s[-1] == 'A':
            s_table[2] += 1
    
    if s_table[0] == 0:
        ans += min(s_table[1:])
    elif sum(s_table[1:]) > 0:
        ans += s_table[0]+min(s_table[1:])
    else:
        ans += s_table[0]-1
    print(ans)
        
    
if __name__ == '__main__':
    main()

Solution (Python):
N = int(input())
 
As = 0
Bs = 0
ABs = 0
BAs = 0
 
for i in range (0, N):
	K = str(input())
	ABs+= K.count('AB')
	if K[0] == 'B':
		if K[-1] == 'A':
			BAs+=1
		else:
			Bs+=1
	elif K[-1] == 'A':
		As+=1

if BAs== 0:
	print(ABs+min(As, Bs))
elif As+Bs>0:
	print(ABs+BAs+min(As, Bs))
else:
	print(ABs+BAs-1)

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n = int(input())

    cnt_BA = cnt_A = cnt_B = cnt_AB = 0
    for _ in range(n):
        s = input().rstrip()
        cnt_AB += 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

    res = cnt_AB + max(0, (cnt_BA - 1)) + min(cnt_A, cnt_B)
    cnt_BA = 1 if cnt_BA >= 1 else 0
    cnt_A = cnt_A - min(cnt_A, cnt_B)
    cnt_B = cnt_B - min(cnt_A, cnt_B)
    if cnt_A != 0 and cnt_BA != 0:
        res += min(cnt_A, cnt_BA)
    elif cnt_B != 0 and cnt_BA != 0:
        res += min(cnt_B, cnt_BA)
    print(res)


if __name__ == '__main__':
    resolve()

Solution (Python):
N = int(input())
cnt = 0
st_cnt = 0
end_cnt =0
same_cnt =0

for k in range(N):
    s = input()
    cnt +=s.count("AB")

    if (s[0] =='B') & (s[-1]=='A'):
        same_cnt += 1
    elif (s[0] =='B'):
        st_cnt +=1
    elif (s[-1] == 'A'):
        end_cnt += 1
if same_cnt==0:
    print(cnt + same_cnt + min(st_cnt, end_cnt))
elif (st_cnt==0) and (end_cnt==0):
    print(cnt+same_cnt-1)
else:print(cnt+same_cnt+min(st_cnt,end_cnt))

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

Solution (Python):
N=int(input())
ans=0
A=0
B=0
ab=0
for _ in range(N):
    S=input()
    ans+=S.count('AB')
    A+=S[-1]=='A'
    B+=S[0]=='B'
    ab+=(S[-1]=='A' and S[0]=='B')

if ab>0 and ab==A==B:
    ans-=1
print(ans+min(A,B))

Solution (Python):
n=int(input())
c1=0
c2=0
c3=0
ans=0
for i in range(n):
    s=input()
    if s[0]=="B" and s[-1]=="A":
        c1+=1
    if s[0]=="B" and s[-1]!="A":
        c2+=1
    if s[0]!="B" and s[-1]=="A":
        c3+=1
    for j in range(len(s)-1):
        if s[j]=="A"and s[j+1]=="B":
            ans+=1
if c1==0:
    ans+=min(n-1,min(c2,c3))
elif c1!=0:
    if c2+c3>0:
        ans+=c1+min(c2,c3)
    if c2+c3==0:
        ans+=c1-1
print(ans)

Solution (Python):
N = int(input())
ans = 0
both = 0
start_B = 0
end_A = 0
for _ in range(N):
    s = input()
    ans += s.count("AB")
    isB = s.startswith("B")
    isA = s.endswith("A")
    if isA and isB:
        both += 1
    if isA:
        end_A += 1
    if isB:
        start_B += 1
ans += min(start_B, end_A)
if start_B == both and both == end_A and start_B != 0:
    ans = max(0, ans - 1)
print(ans)

Solution (Python):
N=int(input())
ans=0
cnt_a,cnt_b,cnt_c=0,0,0
for i in range(N):
    s=input()
    ans+=s.count("AB")
    s=s.replace("AB","")
    if s[0]=="B" and s[-1]=="A":
        cnt_c+=1
    elif s[0]=="B":
        cnt_b+=1
    elif s[-1]=="A":
        cnt_a+=1
if cnt_c==0:
    print(ans+min(cnt_a,cnt_b))
elif cnt_a+cnt_b == 0:
    print(ans+cnt_c-1)
else:
    print(ans+cnt_c+min(cnt_a,cnt_b))

Solution (Python):
N = int(input())
S_list = [input() for x in range(N)]



a_count = 0

b_count = 0

ab_count = 0

for s in S_list:
    if s[0] != "B" and s[-1] == "A":
        a_count += 1
    elif s[0] == "B" and s[-1] != "A":
        b_count += 1
    elif s[0] == "B" and s[-1] == "A":
        ab_count += 1


temp = sum([x.count("AB") for x in S_list])

if ab_count == 0:
    print(temp + min(a_count, b_count))
else:
    
    if a_count == 0 and b_count == 0:
        print(temp + ab_count - 1)

    
    else:
        print(temp + min(a_count, b_count) + ab_count)

Solution (Python):
n = int(input())
ans = 0
cnt_a, cnt_b, cnt_ab  = 0, 0, 0
for i in range(n):
    s = input()
    ans += s.count("AB")
    if s[-1] == "A":
        cnt_a += 1
    if s[0] == "B":
        cnt_b += 1
    if s[0] == "B" and s[-1] == "A":
        cnt_ab += 1

print(ans + min(cnt_a, cnt_b) if cnt_ab < max(cnt_a, cnt_b) or cnt_b == 0 else ans + (cnt_ab - 1))

Solution (Python):
N = int(input())
S = [input() for _ in range(N)]

last_A = []
first_B = []
A_B = []
for i in range(N):
    if (S[i][0] == 'B' and S[i][-1] == 'A'):
        A_B.append(S[i])
    elif (S[i][0] == 'B'):
        first_B.append(S[i])
    elif (S[i][-1] == 'A'):
        last_A.append(S[i])

count = 0
for i in S:
    for j in range(len(i) - 1):
        if i[j] == 'A' and i[j + 1] == 'B':
            count += 1


def calc_comb(sb, fa, sbfa):
    if sbfa == 0:
        return min(sb, fa)
    elif sb == 0 and fa == 0:
        return sbfa - 1
    else:
        return sbfa + min(sb, fa)


print(count + calc_comb(len(first_B), len(last_A), len(A_B)))

Solution (Python):
N = int(input())
S = [input() for _ in range(N)]
 


include = 0
sb = 0
fa = 0
sbfa = 0
for s in S:
    include += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        sbfa += 1
    elif s[0] == 'B':
        sb += 1
    elif s[-1] == 'A':
        fa += 1

def calc_comb(sb, fa, sbfa):
    if sbfa == 0:
        return min(sb, fa)
    elif max(sb, fa)==0:
        return sbfa -1
    else:
        return sbfa + min(sb, fa)

print(include + calc_comb(sb, fa, sbfa))

Solution (Python):
N = int(input())
S = [input() for _ in range(N)]
 


sb = 0
fa = 0
sbfa = 0
for s in S:
    if s[0] == 'B' and s[-1] == 'A':
        sbfa += 1
    elif s[0] == 'B':
        sb += 1
    elif s[-1] == 'A':
        fa += 1

include = sum([x.count("AB") for x in S])

def calc_comb(sb, fa, sbfa):
    if sbfa == 0:
        return min(sb, fa)
    elif max(sb, fa)==0:
        return sbfa -1
    else:
        return sbfa + min(sb, fa)

print(include + calc_comb(sb, fa, sbfa))

Solution (Python):
n = int(input())
s_array = [input() for x in range(n)]
a_count = 0
b_count = 0
ab_count = 0
for s in s_array:
    if s[-1] == "A" and s[0] != "B":
        a_count += 1
    elif s[0] == "B" and s[-1] != "A":
        b_count += 1
    elif s[0] == "B" and s[-1] == "A":
        ab_count += 1
    else:
        pass

res = sum([x.count("AB") for x in s_array])

if n == 1:
    print(res)
elif ab_count == 0:
    print(res + min(a_count, b_count))
elif a_count == 0 and b_count == 0:
    print(res - 1 + ab_count)
else:
    print(res + min(a_count, b_count) + ab_count)

Solution (Python):
n=int(input())
c=0
a=0
b=0
ab=0

for i in range(n):
  s=input()
  c+=s.count("AB")
  if s[0]=="B" and s[-1]=="A":ab+=1
  elif s[0]=="B":b+=1
  elif s[-1]=="A":a+=1

c+=min(a,b)+ab if max(a,b)!=0 else ab-1 if ab>0 else 0
print(c)

Solution (Python):
import sys
input = sys.stdin.buffer.readline




def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))


def main():
	n=II()

	a=0
	b=0
	ab=0
	ans=0

	for _ in range(n):
		s=input().rstrip().decode()
		ans+=s.count("AB")
		if s[0]=="B" and s[-1]=="A":
			ab+=1
		elif s[0]=="B":
			b+=1
		elif s[-1]=="A":
			a+=1

	if ab==0:
		ans+=min(a,b)
	else:
		ans+=ab-1
		if not a==b==0:
			ans+=1+min(a,b)

	print(ans)







if __name__ == "__main__":
	main()

Solution (Python):
n = int(input())
AB = 0
A_B = 0
A = 0
B = 0
for _ in range(n):
    s = input()
    AB += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        A_B += 1
        continue
    if s[0] == 'B':
        B += 1
    if s[-1] == 'A':
        A += 1
ans = 0
if A_B == 0:
    ans = AB + min(B, A)
else:
    if A + B:
        ans = AB + A_B + min(B, A)
    else:
        ans = AB + A_B - 1
print(ans)

Solution (Python):
n = int(input())
xa = 0
by = 0
ba = 0
counter = 0
for _ in range(n):
  s = input()
  counter += s.count('AB')
  if s[0]=='B':
    if s[-1]=='A':
      ba += 1
    else:
      by += 1
  elif s[-1] == 'A':
    xa += 1
if ba == 0:
  counter += min(xa,by)
else:
  if xa+by== 0:
    counter += ba -1
  else:
    counter += ba + min(xa,by)
print(counter)

Solution (Python):
from math import ceil,floor,comb,factorial,gcd,pow,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from copy import deepcopy
from time import time
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

n = INT()
s = [input() for i in range(n)]

a = 0
b = 0
ab = 0
c = 0
for x in s:
    ab += x.count("AB")
    if x[0] == 'B' and x[-1] == 'A':
        c += 1
    elif x[0] == 'B':
        b += 1
    elif x[-1] == 'A':
        a += 1
    
print( ab + max(c-1, 0) + min(a, b) + (1 if a + b != 0 and c > 0 else 0))

Solution (Python):
n = int(input())
hB = set()
tA = set()
cAB = 0
for i in range(n):
    s = input()
    cAB += s.count('AB')
    if s[0] == 'B': hB.add(i)
    if s[-1] == 'A': tA.add(i)
if len(hB&tA)>0:
    if len(hB)-len(hB&tA)>0 or len(tA)-len(hB&tA)>0:
        print(cAB+min(len(hB),len(tA)))
    else:
        print(cAB+min(len(hB),len(tA))-1)
else:
    print(cAB+min(len(hB),len(tA)))

Solution (Python):
n, *ss = open(0).read().split()
ans = 0
inter_count = sum([s.count('AB') for s in ss])
ans += inter_count

_a = sum(s[-1] == 'A' for s in ss)
b_ = sum(s[0] == 'B' for s in ss)
b_a = sum(s[0] == 'B' and s[-1] == 'A' for s in ss)
_a -= b_a
b_ -= b_a

ans += max(0,b_a-1)

if b_a:
    ans += bool(b_)
    b_ -= bool(b_)
    ans += bool(_a)
    _a -= bool(_a)

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

Solution (Python):
n = int(input())
s = [input() for _ in range(n)]

ans, cnt = 0, [0, 0, 0]
for i in s:
    ans += i.count('AB')
    if i[0] == 'B' and i[-1] == 'A':
        cnt[0] += 1
    elif i[0] == 'B':
        cnt[1] += 1
    elif i[-1] == 'A':
        cnt[2] += 1

if cnt[1] + cnt[2] == 0:
    print(ans + max(cnt[0] - 1, 0))
else:
    print(ans + min(cnt[1], cnt[2]) + cnt[0])

Solution (Python):
N = int(input())
res = 0
b_, _a, b_a = 0, 0, 0

for i in range(N):
    s = input()
    res += s.count("AB")
    s = s.replace("AB", "*")
    if s[0] == "B":
        if s[-1] == "A":
            b_a += 1
        else:
            b_ += 1
    elif s[-1] == "A":
        _a += 1

if b_a > 0:
    res += b_a - 1
    if _a > 0:
        res += 1
        _a -= 1
    if b_ > 0:
        res += 1
        b_ -= 1

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

Solution (Python):
n = int(input())

cnt_a = 0   
cnt_b = 0   
cnt_ba = 0  

ans = 0
for _ in range(n):
    s = input()
    ans += s.count('AB')
    if s.endswith('A') and s.startswith('B'):
        cnt_ba += 1
    else:
        if s.endswith('A'):
            cnt_a += 1
        if s.startswith('B'):
            cnt_b += 1

if cnt_ba == 0:
    ans += min(cnt_a, cnt_b)
else:
    ans += cnt_ba-1
    if cnt_a > 0:
        cnt_a -= 1
        ans += 1
    if cnt_b > 0:
        cnt_b -= 1
        ans += 1
    
    ans += min(cnt_a, cnt_b)

print(ans)

Solution (Python):
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_nl = lambda: list(map(int, readline().split()))
in_na = lambda: map(int, read().split())
in_s = lambda: readline().rstrip().decode('utf-8')


def main():

    N = in_n()

    ans = 0
    ar, br, abr = 0, 0, 0
    for i in range(N):
        s = in_s()
        ans += s.count('AB')
        if s[0] == 'B' and s[-1] == 'A':
            abr += 1
        elif s[0] == 'B':
            br += 1
        elif s[-1] == 'A':
            ar += 1

    
    

    t = abr
    if ar > 0:
        ar -= 1
        t += 1
    if br > 0:
        br -= 1
        t += 1
    if t > 1:
        ans += t - 1

    ans += min(ar, br)
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
N = int(input())
S = [input() for _ in range(N)]

AB_cnt = 0
c1 = 0
c2 = 0
c3 = 0


for s in S:
    AB_cnt += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        c1 += 1
    elif s[0] == 'B':
        c2 += 1
    elif s[-1] == 'A':
        c3 += 1
if c1 == 0:
    print(AB_cnt + min(c2,c3))
elif c2 + c3 > 0:
    print(AB_cnt + c1 + min(c2,c3))
else:
    print(AB_cnt + c1 - 1)

Solution (Python):
n = int(input())
s = [str(input()) for _ in range(n)]

ba = 0
bo = 0
oa = 0
ans = 0

for i in range(n):
    ans += s[i].count('AB')
    if s[i][0] == 'B' and s[i][-1] == 'A':
        ba += 1
    elif s[i][0] == 'B':
        bo += 1
    elif s[i][-1] == 'A':
        oa += 1


if ba > 0 and bo + oa > 0:
    ans += ba + min(bo, oa)
if ba > 0 and bo + oa == 0:
    ans += ba - 1
if ba == 0 and bo + oa > 0:
    ans += min(bo, oa)

print(ans)

Solution (Python):
n=int(input())
lb=0
ra=0
ba=0
ans=0

import re

for _ in range(n):
    s=input()

    ans+=s.count('AB')

    if s[0]=='B' and s[-1]=='A':
        ba+=1
    elif s[0]=='B':
        lb+=1
    elif s[-1]=='A':
        ra+=1

if ba>0:
    ans+=ba-1
    ba=1

tmp=min(lb,ra,ba)
ans += 2*tmp

lb-=tmp
ra-=tmp
ba-=tmp

if lb<0:
    lb=0
if ra<0:
    ra=0
if ba<0:
    ba=0

if lb!=0 or ra!=0:
    ans+=min(lb,ra)
    ans+=min(lb,ba)
    ans+=min(ra,ba)


print(ans)

Solution (Python):


def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    N=I()
    cnt=0
    a=0
    b=0
    A="A"
    B="B"
    ab=0
                
    
    for i in range(N):
        s=input()
        cnt+=s.count("AB")
        if s[0]==B and s[-1]==A:
            ab+=1
        elif s[0]==B:
            b+=1
        elif s[-1]==A:
            a+=1
            
    if a==0 and b==0:
        cnt+=ab-1
        if ab==0:
            cnt+=1
    else:
        cnt+=ab
    ans=cnt+min(a,b)
    print(ans)

main()