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
def I(): return int(sys.stdin.readline().rstrip())
def S(): return sys.stdin.readline().rstrip()


N = I()

ans = 0
b_start,a_end,b_start_a_end = 0,0,0

for i in range(N):
    s = S()
    if s[0] == 'B' and s[-1] == 'A':
        b_start_a_end += 1
    elif s[0] == 'B':
        b_start += 1
    elif s[-1] == 'A':
        a_end += 1
    for j in range(len(s)-1):
        if s[j] == 'A' and s[j+1] == 'B':
            ans += 1

if b_start_a_end == 0:
    print(ans+min(b_start,a_end))
else:
    ans += b_start_a_end-1  
    if a_end > 0:
        ans += 1
        a_end -= 1
    if b_start > 0:
        ans += 1
        b_start -= 1
    ans += min(b_start,a_end)
    print(ans)

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

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

a -= b_a
b -= b_a
if a == 0 and b == 0:
  print(ab + max(b_a-1, 0))
else:
  print(ab + min(a, b) + b_a)

Solution (Python):
N = int(input())
S = [input().strip() for _ in range(N)]
C = {"A":0,"B":0,"BA":0}
cnt = 0
for i in range(N):
    s = S[i]
    for j in range(len(s)-2+1):
        if s[j:j+2]=="AB":
            cnt += 1
    if s[0]=="B" and s[-1]=="A":
        C["BA"] += 1
    elif s[0]=="B":
        C["B"] += 1
    elif s[-1]=="A":
        C["A"] += 1
if C["BA"]>0:
    cnt += C["BA"]-1
    if C["B"]>0:
        cnt += 1
        C["B"] -= 1
    if C["A"]>0:
        cnt += 1
        C["A"] -= 1
cnt += min(C["B"],C["A"])
print(cnt)

Solution (Python):
n=int(input())
s=[input() for _ in range(n)]
c,ca,cb,cab=0,0,0,0
for i in range(n):
    n0=len(s[i])
    if s[i][0]=='B':
        if s[i][n0-1]=='A':cab+=1
        else:cb+=1
    elif s[i][n0-1]=='A':ca+=1
    for j in range(1,n0):
        if s[i][j-1]=='A' and s[i][j]=='B':c+=1
ans=c
if cab>0:
    if ca>0:
        ans+=1
        ca-=1
    ans+=cab-1
    if cb>0:
        ans+=1
        cb-=1
ans+=min(ca,cb)
print(ans)

Solution (Python):
N = int(input())
ans = 0
A = 0; B = 0; AB = 0
for i in range(N):
  s = str(input()); n =len(s)
  for i in range(n-1):
    if s[i:i+2] == "AB":
      ans += 1  
  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 and B == 0:
    temp = 0
  elif A == 0 or B ==0:
    temp = 1
  else: 
    temp = min(A,B)+1
  
  ans += temp

else:
  ans += min(A,B)

print(ans)

Solution (Python):
n = int(input())
ab, tail_a, head_b, th_a = 0, 0, 0, 0

for _ in range(n):
    s = input()
    ab += s.count('AB')
    if s[-1] == 'A' and s[0] == 'B': th_a += 1
    elif s[-1] == 'A': tail_a += 1
    elif s[0] == 'B': head_b += 1

if tail_a+head_b == 0 and th_a > 0:
    print(ab + th_a - 1)
else:
    if min(tail_a, head_b) + th_a == n:
        print(ab + min(tail_a, head_b) + th_a - 1)
    else:
        print(ab + min(tail_a, head_b) + th_a)

Solution (Python):
import sys

sys.setrecursionlimit(10**7)
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  
def LI2(): return list(map(int,sys.stdin.readline().rstrip()))  
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())  
def LS2(): return list(sys.stdin.readline().rstrip())  


N = I()

ans = 0
b_start,a_end,b_start_a_end = 0,0,0
for i in range(N):
    s = S()
    if s[0] == 'B' and s[-1] == 'A':
        b_start_a_end += 1
    elif s[0] == 'B':
        b_start += 1
    elif s[-1] == 'A':
        a_end += 1
    for j in range(len(s)-1):
        if s[j] == 'A' and s[j+1] == 'B':
            ans += 1

if b_start_a_end == 0:
    print(ans+min(b_start,a_end))
else:
    ans += b_start_a_end-1
    if a_end > 0:
        ans += 1
        a_end -= 1
    if b_start > 0:
        ans += 1
        b_start -= 1
    ans += min(b_start,a_end)
    print(ans)

Solution (Python):
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

N = int(input())
B_A = 0
start_B = 0
end_A = 0
ans = 0
for _ in range(N):
    s = input()
    ans += s.count('AB')
    if s[0]=='B' and s[-1]=='A':
        B_A += 1
    elif s[0]=='B':
        start_B += 1
    elif s[-1]=='A':
        end_A += 1

if B_A>=1:
    ans += B_A - 1
    B_A = 1
ans += min(B_A, start_B) + min(B_A, end_A) + max(min(start_B - B_A, end_A - B_A), 0)
print(ans)

Solution (Python):
n = int(input())
ba_cnt = 0
b_top_cnt = 0
a_end_cnt = 0

ab = 0
for _ in range(n):
    s = input()
    ab += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        ba_cnt += 1
    elif s[0] == 'B':
        b_top_cnt += 1
    elif s[-1] == 'A':
        a_end_cnt += 1

ans = ab
if ba_cnt == 0:
    ans += min(a_end_cnt, b_top_cnt)
else:
    ans += (ba_cnt-1)
    if a_end_cnt >0:
        a_end_cnt -= 1
        ans += 1
    if b_top_cnt > 0:
        b_top_cnt -= 1
        ans += 1
    ans += min(a_end_cnt,b_top_cnt)

print(ans)

Solution (Python):
import sys
stdin=sys.stdin

ip=lambda: int(sp())
fp=lambda: float(sp())
lp=lambda:list(map(int,stdin.readline().split()))
sp=lambda:stdin.readline().rstrip()

n=ip()
a=[]
b=[]
ans=0
for i in range(n):
  s=sp()
  if s[0]=='B':
    b.append(i)
  if s[-1]=='A':
    a.append(i)
  for j in range(len(s)-1):
    if s[j]=='A' and s[j+1]=='B':
      ans+=1
      
c=len(list(set(a)&set(b)))
a_rest=len(a)-c
b_rest=len(b)-c
if c==0:
  omake=min(a_rest,b_rest)
else:
  if a_rest==b_rest==0:
    omake=c-1
  else:
    omake=c+min(a_rest,b_rest)
  
print(ans+omake)

Solution (Python):
n = int(input())
sm = 0
b_first = 0
a_end = 0
b_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":
            sm += 1
    if s[0]=="B" and s[-1]=="A": b_a += 1    
    elif s[0]=="B": b_first += 1
    elif s[-1]=="A": a_end += 1

ans = sm

if b_a == 0:
    ans += min(b_first,a_end)
elif b_first+a_end==0:
    ans += b_a-1
else:
    ans += b_a + min(b_first, a_end)

print(ans)

Solution (Python):
n = int(input())
ca = 0
cb = 0
cab = 0
ans = 0
for i in range(n):
    a = input()
    if a[0] == "B":
        if a[-1] == "A":
            cab += 1
        else:
            cb += 1
    else:
        if a[-1] == "A":
            ca += 1
    for j in range(len(a)-1):
        if a[j] == "A" and a[j+1] == "B":
            ans += 1
if cab == 0:
    print(ans+min(ca,cb))
else:
    if max(ca,cb) > 0:
        print(ans + cab + min(ca,cb))
    else:
        print(ans + cab - 1)

Solution (Python):
_,*s=open(0).read().split()
a=b=c=d=0
for S in s:a+=S[-1]=='A';b+=S[0]=='B';c+=S[-1]+S[0]=='AB';d+=S.count('AB')
print(d+min(a,b)-(0<a==b==c))

Solution (Python):
_,*s=open(0).read().split()
a=b=c=d=0
for S in s:
 c+=S.count('AB')
 if S[-1]=='A':
  a+=1
  if S[0]!='B':d=1
 if S[0]=='B':
  b+=1
  if S[-1]!='A':d=1
print(c+max(min(a,b)+d-1,0))

Solution (Python):
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    from collections import defaultdict
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    from math import floor, ceil,pi,factorial
    from operator import itemgetter
    def I(): return int(input())
    def MI(): return map(int, input().split())
    def LI(): return list(map(int, input().split()))
    def LI2(): return [int(input()) for i in range(n)]
    def MXI(): return [[LI()]for i in range(n)]
    def SI(): return input().rstrip()
    def printns(x): print('\n'.join(x))
    def printni(x): print('\n'.join(list(map(str,x))))
    inf = 10**17
    mod = 10**9 + 7

    n=I()
    counta=0
    countb=0
    countab=0
    ans=0
    for i in range(n):
        s=SI()
        if s[-1]=="A":
            if s[0]=="B":
                countab+=1
            else:
                counta+=1
        else:
            if s[0]=="B":
                countb+=1
        for i in range(len(s)-1):
            if s[i]=="A" and s[i+1]=="B":
                ans+=1
    if counta>0 and countb>0:
        ans+=countab+1
        counta-=1
        countb-=1
        ans+=min(counta,countb)
    elif counta>0:
        ans+=countab
    elif countb>0:
        ans+=countab
    else:
        ans+=max(0,countab-1)
    print(ans)
                

            
        








if __name__=="__main__":
    main()

Solution (Python):
import bisect,collections,copy,itertools,math,string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())
def main():
    
    n = I()
    ans = 0
    x, y, z = 0, 0, 0

    for _ in range(n):
        s = S()
        ans += s.count("AB")
        if s[0]=="B" or s[-1]=="A":
            if s[0]=="B" and s[-1]=="A":
                x += 1
            elif s[0]=="B":
                z += 1
            else:
                y += 1
    
    if x==0:
        ans += min(y,z)
    else:
        if y==0 or z==0:
            if y==0 and z==0:
                ans += x-1
            else:
                ans += x
        else:
            ans += x + 1 + min(y-1, z-1)

    print(ans)
                


main()

Solution (Python):
n = int(input())
x,y,z = 0,0,0
ans = 0
for _ in range(n):
    s = input()
    for i in range(len(s)-1):
        if s[i] == 'A' and s[i+1] == 'B':
            ans += 1
    if s[0] == 'B' and s[-1] == 'A':
        x += 1
    elif s[0] == 'B':
        y += 1
    elif s[-1] == 'A':
        z += 1
    else:
        pass
if x == 0:
    print(ans+min(y,z))
else:
    if y + z > 0:
        print(ans + x + min(y,z))
    else:
        print(ans + x - 1)

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

kosu = [0,0,0]
ans = 0
for i in range(n):
    s = input()
    ans += s.count('AB')
    if s[0]=="B" and s[-1]=="A":
        kosu[2] += 1
        continue
    if s[0] == "B":
        kosu[1] += 1
    if s[-1] == "A":
        kosu[0] += 1

if kosu[2] == 0:
    ans += min(kosu[0],kosu[1])
else:
    if kosu[0]+kosu[1] >= 1:
        ans += min(kosu[0], kosu[1])+kosu[2]
    else:
        ans += kosu[2]-1

print(ans)

Solution (Python):
from typing import List, Any


def read_int() -> int:
    return int(input().strip())


def read_ints() -> List[int]:
    return list(map(int, input().strip().split(' ')))


def ceil(A, B):
    if A%B == 0:
        return A//B
    return A//B+1

def solve() -> Any:
    N = read_int()
    answer = 0
    
    BxA = 0
    Bx = 0
    xA = 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':
            BxA += 1
        elif S[0] == 'B':
            Bx += 1
        elif S[-1] == 'A':
            xA += 1
    if BxA:
        answer += BxA-1
        if Bx:
            answer += 1
            Bx -= 1
        if xA:
            answer += 1
            xA -= 1
    k = min(Bx, xA)
    Bx -= k
    xA -= k
    answer += k
    return answer


if __name__ == '__main__':
    print(solve())

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

ab = 0
ba = 0
c2 = 0
c3 = 0
for x in s:
    if 'AB' in x:
        ab += x.count('AB')    
    if x[-1] == 'A' and x[0] == 'B':
        ba += 1
    if x[-1] == 'A' and x[0] != 'B':
        c2 += 1
    if x[-1] != 'A' and x[0] == 'B':
        c3 += 1
if ba > 0:
    if c2 + c3 > 0:
        ans = ab + ba + min(c2, c3)
    else: 
        ans = ab + ba - 1
else:
    ans = ab + min(c2, c3)
print(ans)

Solution (Python):
N = int(input())
S = []

ans = 0
end_a = 0
start_b = 0
both = 0
for i in range(N):
    s = input()
    S.append(s)
    ans += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        both += 1
    elif s[-1] == 'A':
        end_a += 1
    elif s[0] == 'B':
        start_b += 1

if both == 0:
    ans += min(start_b, end_a)
else:
    if start_b == end_a == 0:
        ans += both - 1
    else:
        ans += both + min(start_b, end_a)

print(ans)

Solution (Python):

def solve(S):
    N = len(S)
    res = 0
    xa = 0
    bx = 0
    ba = 0

    for s in S:
        if s[-1] == 'A' and s[0] == 'B':
            ba += 1
        else:
            xa += int(s[-1] == 'A')
            bx += int(s[0] == 'B')
        res += s.count('AB')

    if ba == 0:
        return res + min(xa,bx)

    if xa > 0 and bx > 0:
        res += ba + 1
        xa -= 1
        bx -= 1
    elif xa > 0:
        res += ba
        xa -= 1
    elif bx > 0:
        res += ba
        bx -= 1
    else:
        res += ba - 1

    return res + min(xa,bx)

from itertools import permutations
def naive(S):
    
    return max(''.join(x).count('AB') for x in permutations(S))

from random import randrange














N = int(input())
S = [input() for _ in range(N)]
print(solve(S))

Solution (Python):
N = int(input())
cnt, A, B, C = 0, 0, 0, 0
for _ in range(N):
    S = input().rstrip()
    flg = False
    for s in S:
        if s=="A":
            flg=True
        elif flg==True and s=="B":
            cnt += 1
            flg = False
        else: flg = False
    if S[0]=="B": B+=1
    if S[-1]=="A": A+=1
    if S[0]=="B" and S[-1]=="A": C+=1
if A==B==C and A!=0: print(cnt+A-1)
else: print(cnt+min(A,B))

Solution (Python):
n, *S = open(0)
n = int(n)
a = b = ba = c = 0
for i in range(n):
  S[i] = S[i].strip()
  if S[i][-1]=='A' and S[i][0]=='B':
    ba += 1
  else:
    a += S[i][-1]=='A'
    b += S[i][0]=='B'
  c += S[i].count('AB')
if ba == 0:
  print(c + min(a, b))
elif a+b == 0:
  print(c + ba-1)
else:
  print(c + ba + min(a, b))

Solution (Python):
n = int(input())
S = []





ans = 0
c1 = 0
c2 = 0
c3 = 0
for _ in range(n):
  s = input()
  ans += s.count("AB")
  if s.startswith("B") and s.endswith("A"):
    c1 += 1
  elif s.startswith("B"):
    c2 += 1
  elif s.endswith("A"):
    c3 += 1
if c2 + c3 > 0:
  ans += min(c1+c2, c1+c3)
else:
  if c1 != 0:
    ans += c1 - 1
print(ans)

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

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

import re
cnt = 0
for i in range(n):
    cnt += len(re.findall("AB",s[i]))
    si = s[i].replace("AB","x")
    s[i] = si
ac= 0
bc = 0
abc = 0
for i in range(n):
    if s[i]:
        if  s[i][-1]=="A" and s[i][0]=="B":
            abc+=1
        elif s[i][-1]=="A":
            ac+=1
        elif s[i][0]=="B":
            bc+=1
        

mn=min(ac,bc)
cnt += mn
if ac or bc:
    cnt += abc
else:
    cnt+=max(abc-1,0)
print(cnt)

Solution (Python):
n = int(input())
lasta = 0
firstb = 0
btoa = 0
cnt = 0
for _ in range(n):
    S = input()
    cnt += S.count('AB')
    if S[0] == 'B' and S[-1] != 'A':
        firstb += 1
    elif S[-1] == 'A' and S[0] != 'B':
        lasta += 1
    elif S[0] == 'B' and S[-1] == 'A':
        btoa += 1
if btoa == 0:
    print(cnt + min(lasta, firstb))
else:
    print(cnt + btoa + (min(firstb, lasta) if firstb + lasta > 0 else -1))

Solution (Python):
import sys
from sys import exit
from collections import deque
from bisect import bisect_left, bisect_right, insort_left, insort_right 
from heapq import heapify, heappop, heappush
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import reduce
from math import gcd, sin, cos, tan, asin, acos, atan, degrees, radians

sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9+7

def lcm(x,y):
    return x*y//gcd(x,y)
def lgcd(l):
    return reduce(gcd,l)
def llcm(l):
    return reduce(lcm,l)
def powmod(n,i,mod):
    return pow(n,mod-1+i,mod) if i<0 else pow(n,i,mod)
def div2(x):
    return x.bit_length()
def div10(x):
    return len(str(x))-(x==0)
def perm(n,mod=None):
    ans = 1
    for i in range(1,n+1):
        ans *= i
        if mod!=None:
            ans %= mod
    return ans
def intput():
    return int(input())
def mint():
    return map(int,input().split())
def lint():
    return list(map(int,input().split()))
def ilint():
    return int(input()), list(map(int,input().split()))
def judge(x, l=['Yes', 'No']):
    print(l[0] if x else l[1])
def lprint(l, sep='\n'):
    for x in l:
        print(x, end=sep)
def ston(c, c0='a'):
    return ord(c)-ord(c0)
def ntos(x, c0='a'):
    return chr(x+ord(c0))
class counter(dict):
    def __init__(self, *args):
        super().__init__(args)
    def add(self,x,d=1):
        self.setdefault(x,0)
        self[x] += d
    def list(self):
        l = []
        for k in self:
            l.extend([k]*self[k])
        return l
class comb():
    def __init__(self, n, mod=None):
        self.l = [1]
        self.n = n
        self.mod = mod
    def get(self,k):
        l,n,mod = self.l, self.n, self.mod
        k = n-k if k>n//2 else k
        while len(l)<=k:
            i = len(l)
            l.append(l[i-1]*(n+1-i)//i if mod==None else (l[i-1]*(n+1-i)*powmod(i,-1,mod))%mod)
        return l[k]
def pf(x):
    C = counter()
    p = 2
    while x>1:
        k = 0
        while x%p==0:
            x //= p
            k += 1
        if k>0:
            C.add(p,k)
        p = p+2-(p==2) if p*p<x else x
    return C

N=intput()
S=[input() for _ in range(N)]
A,B,BA=0,0,0
ans=0
for s in S:
    ans+=s.count('AB')
    if s[0]=='B' and s[-1]=='A':
        BA+=1
    elif s[0]=='B':
        B+=1
    elif s[-1]=='A':
        A+=1
ans+=min(A,B)+BA-int(A==B==0 and BA>0)
print(ans)

Solution (Python):
f=1
a=0
b=0
c=0

for i in range(int(input())):
  s=input()
  if s[0]=="B":
    b+=1
  if s[-1]=="A":
    a+=1
  if (not(s[0]=="B" and s[-1]=="A"))and(s[0]=="B" or s[-1]=="A"):
    f=0
  for j in range(len(s)-1):
    if s[j:j+2]=="AB":
      c+=1
if min(a,b)==0:
  f=0
print(min(a,b)+c-f)

Solution (Python):
import sys



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


def input_int():
    return int(input())


def input_int_list():
    return [int(i) for i in input().split()]


def main():
    n = input_int()
    cnt = {"_A": 0, "B_": 0, "B_A": 0}
    ans = 0
    for _ in range(n):
        s = input()
        if s[0] == "B" and s[-1] == "A":
            cnt["B_A"] += 1
        elif s[0] == "B":
            cnt["B_"] += 1
        elif s[-1] == "A":
            cnt["_A"] += 1
        
        for i in range(len(s) - 1):
            if s[i:i + 2] == "AB":
                ans += 1

    
    
    if cnt["B_A"] > 1:
        ans += cnt["B_A"] - 1
        cnt["B_A"] = 1
    
    if cnt["_A"] > 0 and cnt["B_"] > 0 and cnt["B_A"] > 0:
        ans += 2
        cnt["_A"] -= 1
        cnt["B_"] -= 1
        cnt["B_A"] -= 1
    

    ans += min(sorted([cnt["_A"], cnt["B_"], cnt["B_A"]])[1:])

    print(ans)
    return


if __name__ == "__main__":
    main()

Solution (Python):
n = int(input())
cnt_AB = 0
cnt_xxA = 0
cnt_Bxx = 0
cnt_BxA = 0
for i in range(n):
    s = input()
    cnt_AB += s.count('AB')
    if s[-1] == 'A' and s[0] != 'B':
        cnt_xxA += 1
    if s[0] == 'B' and s[-1] != 'A':
        cnt_Bxx += 1
    if s[-1] == 'A' and s[0] == 'B':
        cnt_BxA += 1

if cnt_BxA == 0:
    print(cnt_AB + min(cnt_xxA, cnt_Bxx))
else:
    if cnt_Bxx+cnt_xxA > 0:
        print(cnt_AB + cnt_BxA + min(cnt_xxA, cnt_Bxx))
    else:
        print(cnt_AB + cnt_BxA - 1)

Solution (Python):
n = int(input())
cnt_AB = 0
cnt_xxA = 0
cnt_Bxx = 0
cnt_BxA = 0
for i in range(n):
    s = input()
    cnt_AB += s.count('AB')
    if s[-1] == 'A':
        cnt_xxA += 1
    if s[0] == 'B':
        cnt_Bxx += 1
    if s[-1] == 'A' and s[0] == 'B':
        cnt_BxA += 1

cnt_xxA -= cnt_BxA
cnt_Bxx -= cnt_BxA

if cnt_BxA == 0:
    print(cnt_AB + min(cnt_xxA, cnt_Bxx))
else:
    if cnt_Bxx+cnt_xxA > 0:
        print(cnt_AB + cnt_BxA + min(cnt_xxA, cnt_Bxx))
    else:
        print(cnt_AB + cnt_BxA - 1)

Solution (Python):

import collections as cl
import sys


def II():
    return int(sys.stdin.readline())


def MI():
    return map(int, sys.stdin.readline().split())


def LI():
    return list(map(int, sys.stdin.readline().split()))


def main():
    N = II()

    words = []
    starts_with_B = 0
    end_with_A = 0
    contain_AB = 0
    starts_with_B_and_end_with_A = 0
    for i in range(N):
        word = input()
        words.append(word)
        contain_AB += len(word) - len(word.replace("AB", "_"))

        if word[0] == "B" and word[-1] == "A":
            starts_with_B_and_end_with_A += 1
        elif word[0] == "B":
            starts_with_B += 1
        elif word[-1] == "A":
            end_with_A += 1

    if starts_with_B_and_end_with_A == 0:
        print(contain_AB + min(starts_with_B, end_with_A))
        return
    if starts_with_B + end_with_A == 0:
        print(contain_AB + starts_with_B_and_end_with_A - 1)
        return
    print(contain_AB + starts_with_B_and_end_with_A +
          min(starts_with_B, end_with_A))


main()

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

s1,s2,s3,s4=[],[],[],[]
ans=0
for i in range(N):
  ans += s[i].count('AB')
  if s[i][0]=='B' and s[i][-1]=='A':
    s1.append(s[i])
  elif s[i][-1]=='A':
    s2.append(s[i])
  elif s[i][0]=='B':
    s3.append(s[i])
  else:
    s4.append(s[i])
    
if len(s2) and len(s3):
  ans += len(s1)+1
  ans += min(len(s2)-1,len(s3)-1)
  
elif len(s1) and len(s2):
  ans += len(s1)
  
elif len(s1) and len(s3):
  ans += len(s1)
  
elif len(s1):
  ans += len(s1)-1

print(ans)

Solution (Python):
n = int(input())
ans = 0
s = []
ryotan = 0
atama = 0
oshiri = 0
for _ in range(n):
    _s = input()
    if _s[0] == "B" and _s[-1] == "A":
        ryotan += 1
    elif _s[0] == "B":
        atama += 1
    elif _s[-1] == "A":
        oshiri += 1
    A_flag = 0
    for c in _s:
        if c == "A" and A_flag == 0:
            A_flag = 1
        elif A_flag:
            if c == "B":
                ans += 1
                A_flag = 0
            elif c == "A":
                continue
            else:
                A_flag = 0


if ryotan > 1:
    ans += ryotan - 1
if ryotan > 0:
    if atama > 0:
        ans += 1
        atama -= 1
    if oshiri > 0:
        ans += 1
        oshiri -= 1
ans += min(atama, oshiri)
print(ans)

Solution (Python):
import sys, math
from functools import lru_cache
import numpy as np
from collections import defaultdict
sys.setrecursionlimit(10**9)
MOD = 10**9+7

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return map(int, input().split())

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]


def main():
    N = ii()
    S = [input() for i in range(N)]

    k = sum(S[i].count('AB') for i in range(N))

    c = sum(1 for i in range(N) if S[i][-1] == 'A' and S[i][0] == 'B')
    a = sum(1 for i in range(N) if S[i][-1] == 'A') - c
    b = sum(1 for i in range(N) if S[i][0] == 'B') - c

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


if __name__ == '__main__':
    main()

Solution (Python):
N = int(input())
T, c1, c2, c3 = 0, 0, 0, 0
for i in range(N):
    S = input()
    T += S.count('AB')
    if S[0] == 'B' and S[-1] == 'A':
        c1 += 1
    elif S[-1] == 'A':
        c2 += 1
    elif S[0] == 'B':
        c3 += 1
if c2 == 0 and c3 == 0:
    print(T + max(c1 - 1, 0))
else:
    print(T + c1 + min(c2, c3))

Solution (Python):
N=int(input())
a=0
b=0
ab=0
ans=0
for _ in range(N):
    s=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:
    print(ans+min(a,b))
else:
    if a==0 and b==0:
        print(ans+ab-1)
    else:
        print(ans+min(a+ab,b+ab))

Solution (Python):
import collections
c = 0
cc = collections.Counter()
for _ in range(int(raw_input())):
	w = raw_input()
	for u in range(len(w)-1):
		if w[u:u+2] == 'AB': c+=1
	w = w.replace('AB','')
	if len(w) == 1:
		s = (w[0] if w[0] == 'A' or w[0] == 'B' else '')
	if len(w) >= 2:
		s = (w[0] if w[0] == 'A' or w[0] == 'B' else '') + (w[-1] if w[-1] == 'A' or w[-1] == 'B' else '')
	
	if s: cc[s]+=1
q= 0 
if cc['BA']:
	q += cc['BA'] -1
	if cc['A']:
		cc['A']-=1
		q+=1 
	if cc['B']:
		cc['B']-=1
		q+=1 
print c + q + min(cc['A']+cc['AA'],cc['B']+cc['BB'])
"""
A
AA
B
BB
AB
BA

 A - [BA - BA - BA - BA - BA - BA]  - B 
 A - B 



    [AB - AB - AB - AB - AB - AB ]

    A - B - A  - B  

"""

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

_a = 0
b_ = 0
b_a = 0

cnt = 0

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

    sa = False
    sb = False
    if s[0] == "B":
        sb = True
    if s[-1] == "A":
        sa = True

    if sa and sb:
        b_a += 1
    elif sa:
        _a += 1
    elif sb:
        b_ += 1

    for j in range(len(s)-1):
        if s[j:j+2] == "AB":
            cnt += 1

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

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

Solution (Python):
n=int(input())
ans=0
a=[0]*n
b=[0]*n
for i in range(n):
  s=input()
  ans+=s.count('AB')
  if s[-1]=='A':a[i]=1
  if s[0]=='B':b[i]=1
m=min(sum(a),sum(b))
ans+=m
if m:
  for i,j in zip(a,b):
    if i+j and i*j==0:break
  else:ans-=1
print(ans)

Solution (Python):
def main():
    N = int(input())
    S = [input() for _ in range(N)]
    
    
    
    c_a, c_b, c_ba = 0, 0, 0
    ans = 0
    for s in S:
        if s[0] == 'B' and s[-1] == 'A':
            c_ba += 1
        elif s[-1] == 'A':
            c_a += 1
        elif s[0] == 'B':
            c_b += 1
        ans += len(s.split('AB')) - 1
    ans += max(0, c_ba - 1)
    if c_ba > 0:
        if c_a > 0:
            c_a -= 1
            ans += 1
        if c_b > 0:
            c_b -= 1
            ans += 1
    ans += min(c_a, c_b)
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
N = int(input())
c1 = 0
c2 = 0
c3 = 0
ans = 0
for _ 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':
        c3 += 1
    elif s[0] == 'B':
        c2 += 1
    elif s[-1] == 'A':
        c1 += 1


if c3 == 0:
    ans += min(c1, c2)
elif c1 == c2 == 0:
    ans += c3 - 1
elif c1 == 0 or c2 == 0:
    ans += c3
else:
    ans += min(c1, c2) + c3
print(ans)

Solution (Python):
N = int(input())
c1 = 0
c2 = 0
c3 = 0
ans = 0
for _ 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':
        c3 += 1
    elif s[0] == 'B':
        c2 += 1
    elif s[-1] == 'A':
        c1 += 1


if c3 == 0:
    ans += min(c1, c2)
elif c1 == c2 == 0:
    ans += c3 - 1
elif c1 == 0 or c2 == 0:
    ans += c3
else:
    ans += min(c1 - 1, c2 - 1) + c3 + 1
print(ans)

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

n = 0
Acount, Bcount,both = 0,0,0
for a in A:
    n += a.count("AB")
    if (a[0]=="B")&(a[-1]=="A"):both+=1
    elif a[0] == "B":Bcount+=1
    elif a[-1] == "A":Acount+=1


n += min(Acount,Bcount)
if Acount+Bcount>0:n += both
elif both>0:n += both-1
print(n)

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

n = 0
Acount, Bcount,both = 0,0,0
for a in A:
    n += a.count("AB")
    if (a[0]=="B")&(a[-1]=="A"):both+=1
    elif a[0] == "B":Bcount+=1
    elif a[-1] == "A":Acount+=1


n += min(Acount,Bcount)
if Acount+Bcount>0:n += both
elif both>0:n += both-1
print(n)

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

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

Solution (Python):
N = int(input())
ans = 0
a, b, ab = 0, 0, 0
for _ 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
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())

cnt = 0
A = 0
B = 0
AB = 0

for _ in range(N):
  s = input()
  if s[0] == 'B':
    B += 1
  if s[-1] == 'A':
    A += 1
  if s[-1] == 'A' and s[0] == 'B':
    AB += 1
  for i in range(len(s)-1):
    if s[i] == 'A' and s[i+1] == 'B':
      cnt += 1
    
cnt += min(A,B)
if A == AB and B == AB and AB > 0:
  cnt -= 1
  
print(cnt)

Solution (Python):
import sys
import itertools

import time
import math
import heapq
from collections import defaultdict
from collections import Counter
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines



N = int(input())
ans = 0

end_a = 0
start_b = 0
both = 0
for i in range(N):
    S = input()
    ans += S.count("AB")
    if S[-1] == 'A' and S[0] == 'B':
        both += 1
    elif S[-1] == 'A':
        end_a += 1
    elif S[0] == 'B':
        start_b += 1

if both == 0:
    ans += min(start_b, end_a)
else:
    if start_b + end_a > 0:
        ans += both + min(start_b, end_a)
    else:
        ans += both - 1















print(ans)

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

ans = 0
ab = 0
tail_a = 0
head_b = 0

for _ in range(N):
    s = input()
    ans += s.count('AB')

    if s[-1] == 'A' and s[0] == 'B':
        ab += 1
    elif s[-1] == 'A' and s[0] != 'B':
        tail_a += 1
    elif s[-1] != 'A' and s[0] == 'B':
        head_b += 1

if ab == 0:
    print(ans+min(tail_a, head_b))
elif ab > 0 and max(tail_a, head_b) > 0:
    print(ans+ab+min(tail_a, head_b))
elif max(tail_a, head_b) == 0:
    print(ans+ab-1)

Solution (Python):
n = int(input())
last_a_cnt = 0
top_b_cnt = 0
last_a_top_b_cnt = 0
ab_cnt = 0

for _ in range(n):
    s = input()
    ab_cnt += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A': last_a_top_b_cnt += 1
    elif s[0] == 'B' and s[-1] != 'A': top_b_cnt += 1
    elif s[0] != 'B' and s[-1] == 'A': last_a_cnt += 1


if last_a_cnt > 0:
    ans = 0
    last_a_cnt -= 1
    ans += last_a_top_b_cnt    
    ans += min(last_a_cnt+1, top_b_cnt)
    ans += ab_cnt

else:
    ans = 0
    if last_a_top_b_cnt > 0:
        ans += (last_a_top_b_cnt-1)
        ans += min(1, top_b_cnt)
    ans += ab_cnt

print(ans)