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):
n = int(input())
ans = 0
tail_a_cnt = 0
top_b_cnt = 0
top_b_tail_a = 0
for i in range(n):
    s = list(input())
    top_b = False
    tail_a = False
    
    for c in range(len(s)):
        if c == 0:
            if s[c] == 'B':
                top_b = True
        else:
            if s[c] == 'B' and s[c-1] == 'A':
                ans += 1
        
        if c == len(s)-1 and s[c]=='A':
            tail_a = True
            
    top_b_cnt += top_b
    tail_a_cnt += tail_a
    top_b_tail_a += top_b*tail_a
     
ans += min(top_b_cnt, tail_a_cnt)
if top_b_cnt == tail_a_cnt == top_b_tail_a and top_b_cnt>0:
    ans -= 1
    
print(ans)

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

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

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

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

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

ab=0
a=0
b=0
boa=0

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

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

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


c = 0
ac = 0
bc = 0
abc = 0
for i in range(n):
    c += s[i].count('AB')
    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

if(abc == 0):
    print(c + min(ac,bc))
elif(ac + bc == 0):
    print(c + abc - 1)
else:
    print(c + abc + min(ac,bc))

Solution (Python):
n= int(input())
bdic = {'A':0,'B':1,'O':2}
aot = [[0 for i in range(3)] for i in range(3)]
ans=0
for i in range(n):
    s=input()
    subab=0
    for i in range(len(s)-1):
        if s[i]=='A' and s[i+1]=='B':subab+=1
    ans += subab
    f = 'O' if not s[0]  in bdic.keys() else s[0]
    l = 'O' if not s[-1] in bdic.keys() else s[-1]
    aot[bdic[f]][bdic[l]]+=1

oa = aot[bdic['O']][bdic['A']]+aot[bdic['A']][bdic['A']]
bo = aot[bdic['B']][bdic['O']]+aot[bdic['B']][bdic['B']]
ab = aot[bdic['A']][bdic['B']]
ba = aot[bdic['B']][bdic['A']]

if   oa==0 and bo==0:ans+=max(0,ba-1)
elif oa==0 and bo!=0:ans+=min(bo,ba)+max(0,ba-bo)
elif bo==0 and oa!=0:ans+=min(oa,ba)+max(0,ba-oa)
else:                ans+=min(oa,bo)+ba
print(ans)

Solution (Python):
import sys

input = sys.stdin.readline


def main():
    N = int(input())
    S = [""] * N
    for i in range(N):
        S[i] = input().rstrip()

    xABx = 0
    xxxA = 0
    Bxxx = 0
    BxxA = 0
    for s in S:
        xABx += s.count("AB")
        if s[0] == "B" and s[-1] == "A":
            BxxA += 1
        elif s[0] == "B":
            Bxxx += 1
        elif s[-1] == "A":
            xxxA += 1

    if BxxA == 0:
        ans = xABx + min(xxxA, Bxxx)
    else:
        if xxxA == Bxxx == 0:
            ans = xABx + (BxxA - 1)
        else:
            ans = xABx + BxxA + min(xxxA, Bxxx)
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
import sys
def input(): return sys.stdin.readline().rstrip()
def main():
    n=int(input())
    cunt_a=0
    cunt_b=0
    cunt_ba=0
    cunt_ab=0
    for i in range(n):
        s=input()
        if s[0]=='B' and s[-1]=='A':
            cunt_ba+=1
        elif s[0]=='B': 
            cunt_b+=1
        elif s[-1]=='A':
            cunt_a+=1
        for j in range(len(s)-1):
            if s[j:j+2]=="AB":
                cunt_ab+=1
    if cunt_a==0 and cunt_b==0 and cunt_ba>0:
        print(cunt_ab+cunt_ba-1)
    else:
        print(cunt_ab+cunt_ba+min(cunt_a,cunt_b))
    
if __name__=='__main__':
    main()

Solution (Python):
import sys
def input(): return sys.stdin.readline().rstrip()
def main():
    n=int(input())
    cunt_a=0
    cunt_b=0
    cunt_ba=0
    cunt_ab=0
    for i in range(n):
        s=input()
        if s[0]=='B' and s[-1]=='A':
            cunt_ba+=1
        elif s[0]=='B': 
            cunt_b+=1
        elif s[-1]=='A':
            cunt_a+=1
        for j in range(len(s)-1):
            if s[j:j+2]=="AB":
                cunt_ab+=1
    if cunt_a==0 and cunt_b==0 and cunt_ba>0:
        print(cunt_ab+cunt_ba-1)
    else:
        print(cunt_ab+cunt_ba+min(cunt_a,cunt_b))
    
if __name__=='__main__':
    main()

Solution (Python):
import sys

def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))

def DD2(d1,d2,init=0): return [[init]*d2 for _ in range(d1)]
def DD3(d1,d2,d3,init=0): return [DD2(d2,d3,init) for _ in range(d1)]

def to_bin(x: int) -> str: return format(x, 'b') 
def to_oct(x: int) -> str: return format(x, 'o') 
def to_hex(x: int) -> str: return format(x, 'x') 
MOD=10**9+7
def divc(x,y) -> int: return -(-x//y)
def divf(x,y) -> int: return x//y
def gcd(x,y):
    while y: x,y = y,x%y
    return x
def lcm(x,y): return x*y//gcd(x,y)
def enumerate_divs(n):
    """Return a tuple list of divisor of n"""
    return [(i,n//i) for i in range(1,int(n**0.5)+1) if n%i==0]
def get_primes(MAX_NUM=10**3):
    """Return a list of prime numbers n or less"""
    is_prime = [True]*(MAX_NUM+1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(MAX_NUM**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i*2, MAX_NUM+1, i): is_prime[j] = False
    return [i for i in range(MAX_NUM+1) if is_prime[i]]
def prime_factor(n):
    """Return a list of prime factorization numbers of n"""
    res = []
    for i in range(2,int(n**0.5)+1):
        while n%i==0: res.append(i); n //= i
    if n != 1: res.append(n)
    return res

from itertools import accumulate as acc, combinations as combi, product, combinations_with_replacement as combi_dup
from collections import deque, Counter
from heapq import heapify, heappop, heappush
from bisect import bisect_left


def main():
    n = II()
    ss = [IS() for i in range(n)]
    ab_type = {}
    ab_type['_ab_'] = 0
    ab_type['b__a'] = 0
    ab_type['___a'] = 0
    ab_type['b___'] = 0
    for s in ss:
        for i in range(len(s)-1):
            if s[i:i+2] == 'AB':
                ab_type['_ab_'] += 1
        if s[0] == 'B' and s[-1] == 'A':
            ab_type['b__a'] += 1
        elif s[-1] == 'A':
            ab_type['___a'] += 1
        elif s[0] == 'B':
            ab_type['b___'] += 1
    cnt = 0
    cnt += ab_type['_ab_']
    if ab_type['b__a'] > 0:
        cnt += ab_type['b__a']-1
        if ab_type['___a'] > 0:
            cnt += 1
            ab_type['___a'] -= 1
        if ab_type['b___'] > 0:
            cnt += 1
            ab_type['b___'] -= 1
    cnt += min(ab_type['___a'], ab_type['b___'])
    print(cnt)

if __name__ == '__main__':
    main()

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

mid_ab = 0
la_fb = 0
last_a = 0
first_b = 0

for s in moji:
    mojiretu=len(s)
    if s[0] == 'B' and s[-1] == 'A':
        la_fb += 1
    elif s[0] == 'B':
        first_b += 1
    elif s[-1] == 'A':
        last_a += 1
    for j in range(mojiretu-1):
        if s[j] == 'A' and s[j+1] == 'B':
            mid_ab += 1

if la_fb == 0:
    ans = mid_ab+min(last_a,first_b)
elif last_a == first_b == 0 and la_fb> 0:
    ans = mid_ab+la_fb-1
else:
    if la_fb <= abs(last_a-first_b):
        ans = mid_ab+min(last_a,first_b)+la_fb
    else:
        ans = mid_ab+max(last_a,first_b)+(la_fb-abs(last_a-first_b))
print(ans)

Solution (Python):
n = int(input())
ans = 0
a = 0
b = 0
ryou = 0
for _ in range(n):
    tmp = input()
    ans += tmp.count('AB')
    if tmp[0] == 'B':
        if tmp[-1] == 'A':
            ryou += 1
        else:
            b += 1
    elif tmp[-1] == 'A':
        a += 1

if ryou > 1:
    ans += (ryou-1)
    ryou = 1
if ryou == 1:
    if a >= 1:
        ans += 1
        a -= 1
    if b>=1:
        ans += 1
        b-=1

ans += min(a,b)

print(ans)

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

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

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

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

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

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

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

prev_B = 0
back_A = 0
AB_num = 0
back_A_prev_B = 0
for i in range(N):
    s = input()
    if s[0] == "B":
        prev_B += 1
    if s[len(s)-1] == "A":
        back_A += 1
    if s[0] == "B" and s[len(s)-1] == "A":
        back_A_prev_B += 1
    for j in range(len(s)-1):
        if s[j] == "A" and s[j+1] == "B":
            AB_num += 1

if back_A_prev_B == prev_B and back_A_prev_B == back_A and back_A_prev_B != 0:
    print(AB_num + min(prev_B-1, back_A-1))
else:
    print(AB_num + min(prev_B, back_A))

Solution (Python):
N = int(input())
S = [input() for _ in range(N)]
count = 0
l = []
A,B,BA = 0,0,0
for s in S:
  c = s.count("AB")
  count += c
  if s[-1] == "A" or s[0] == "B":
    l.append(s[0] + s[-1])
    if s[-1] == "A" and s[0] == "B":
      BA += 1
    elif s[-1] == "A":
      A += 1
    elif s[0] == "B":
      B += 1
ans = 0
if BA == 0:
  ans = min(A,B)
elif A+B > 0:
  ans = BA + min(A,B)
elif  A+B == 0:
  ans = BA -1 + min(A,B)
print(count + ans)

Solution (Python):
MOD = 10 ** 9 + 7
INF = 10 ** 11
import sys
sys.setrecursionlimit(100000000)

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

    cnt = 0
    ba = 0
    a = 0
    b = 0
    for s in S:
        for i in range(len(s) - 1):
            if s[i] == 'A' and s[i + 1] == 'B':
                cnt += 1
        if s[0] == 'B' and s[-1] == 'A':
            ba += 1
        elif s[0] == 'B':
            b += 1
        elif s[-1] == 'A':
            a += 1
    
    if a > 0 and b > 0:
        cnt += ba + 1 + min(a - 1,b - 1)
    elif a > 0:
        cnt += ba
    elif b > 0:
        cnt += ba
    else:
        if ba > 0:
            cnt += ba - 1
    print(cnt)
if __name__ == '__main__':
    main()

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

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

count = 0
xxxa = 0
bxxx = 0
bxxxa = 0
for st in s_l:
    if 'AB' in st:
        count += st.count('AB')
    if st.endswith('A'):
        if st.startswith('B'):
            bxxxa += 1
        else:
            xxxa += 1
    elif st.startswith('B'):
        bxxx += 1

if max(xxxa,bxxx) == 0:
    count += max(0, bxxxa - 1)
    print(count)
    exit()

while min(xxxa,bxxx,bxxxa) > 0:
    xxxa -= 1
    bxxx -= 1
    bxxxa -= 1
    count += 2
count += bxxxa
count += min(xxxa,bxxx)
print(count)

Solution (Python):
import re

n = int(input())
w = x = y = z = 0
for i in range(n):
    s = input()
    t = re.sub(r'AB', "X", s)
    w += len(s) - len(t)
    if s[0] == "B":
        if s[-1] == "A":
            x += 1
        else:
            y += 1
    elif s[-1] == "A":
        z += 1
if x > 1:
    w += x - 1
    x = 1
if max(x, y, z) == y:
    w += x
    w += z
elif max(x, y, z) == z:
    w += x
    w += y
print(w)

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

ans = 0
tail_A = 0
head_B = 0
head_B_and_tail_A = 0

for i in range(N):
    s = str(input())
    ans += s.count("AB")

    if s[0]=="B":
        if s[-1]=="A":
            head_B_and_tail_A += 1
        else:
            head_B += 1
    elif s[-1]=="A":
        tail_A += 1

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

use_head_B_and_tail_A = min(head_B_and_tail_A,tail_A,head_B)
head_B_and_tail_A -= use_head_B_and_tail_A
tail_A -= use_head_B_and_tail_A
head_B -= use_head_B_and_tail_A
ans += 2*use_head_B_and_tail_A


use_num = min(head_B_and_tail_A,tail_A)
head_B_and_tail_A -= use_num
tail_A -= use_num
ans += use_num

use_num = min(head_B_and_tail_A,head_B)
head_B_and_tail_A -= use_num
head_B -= use_num
ans += use_num

use_num = min(tail_A,head_B)

ans += use_num

print(ans)

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

Solution (Python):


n = int(input())
strings = []
for _ in range(n):
    strings.append(input())

ans = 0
head_b = tail_a = both = 0
for s in strings:
    ans += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        both += 1
    elif s[0] == 'B':
        head_b += 1
    elif s[-1] == 'A':
        tail_a += 1

if both == 0:
    ans += min(head_b, tail_a)
elif head_b + tail_a == 0:
    ans += max(both - 1, 0)
else:
    ans += both + min(head_b, tail_a)
print(ans)

Solution (Python):
n=int(input())
s=[input() for _ in range(n)]
ans=sum([si.count('AB') for si in s])
endA=len([si for si in s if si[-1]=='A'])
startB=len([si for si in s if si[0]=='B'])
AB=len([si for si in s if si[0]=='B' and si[-1]=='A'])
if endA*startB==0:
      print(ans)
elif AB==endA and AB==startB:
      print(ans+AB-1)
else:
      print(ans+min(endA,startB))

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

ans = 0
top_b = 0
last_a = 0
top_b_and_last_a = 0

for _ in range(N):
    s = input()
    ans += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        top_b_and_last_a += 1
    elif s[0] == "B":
        top_b += 1
    elif s[-1] == "A":
        last_a += 1

ans += max(0, top_b_and_last_a - 1)
if top_b_and_last_a and top_b:
    top_b -= 1
    ans += 1
if top_b_and_last_a and last_a:
    last_a -= 1
    ans += 1
ans += min(top_b, last_a)

print(ans)

Solution (Python):
def solve():
    n = int(input())
    s = []
    ans = 0
    acnt = 0
    bcnt = 0
    bacnt = 0
    for i in range(n):
        s_i = input()
        ans += s_i.count('AB')
        s_i.replace('AB', '')
        if s_i[0] == 'B' and s_i[-1] == 'A':
            bacnt += 1
        elif s_i[0] == 'B':
            bcnt += 1
        elif s_i[-1] == 'A':
            acnt += 1

    
    if bacnt == 0:
        ans += min(acnt, bcnt)
    elif acnt == 0 and bcnt == 0:
        ans += bacnt-1
    else:
        ans += bacnt + min(acnt, bcnt)

    print(ans)

solve()

Solution (Python):
n=int(input())
l=[0,0,0,0]
ans=0
for i in range(n):
    s=input()
    ans+=s.count("AB")
    l[2*int(s[0]=="B")+1*int(s[-1]=="A")]+=1

if l[-1]:
    ans+=l[-1]-1
    if l[1]:
        l[1]-=1
        ans+=1
    if l[2]:
        l[2]-=1
        ans+=1
print(ans+min(l[1:3]))

Solution (Python):
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


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


def S(): return input()


def MS(): return map(str, input().split())


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


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


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


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


def print_matrix(mat):
    for i in range(len(mat)):
        print(*mat[i])


YNL = {False: 'No', True: 'Yes'}
YNU = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()

nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']



show_flg = False


def main():
    N = I()
    s = []

    for i in range(N):
        s.append(S())

    ans = 0
    a = 0
    b = 0
    dup = 0

    for i in range(N):
        if s[i][0] == 'B':
            b += 1
        if s[i][-1] == 'A':
            a += 1
        if s[i][0] == 'B' and s[i][-1] == 'A':
            dup += 1
        for j in range(1, len(s[i])):
            if s[i][j-1] == 'A' and s[i][j] == 'B':
                
                ans += 1

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


if __name__ == '__main__':
    main()

Solution (Python):
import sys
stdin = sys.stdin
 
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n = ni()
ans = 0
a=0
b=0
c=0

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

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

print(ans)

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

acnt =0
bcnt =0
ecnt =0
cnt=0
nomal =0

for i in range(n):
    nomal += s[i].count('AB')
    t=0
    if s[i][0] == 'B':
        bcnt += 1
        cnt+=1
        t+=1
    if s[i][-1] == 'A':
        acnt += 1
        if not t:
            cnt+=1
        t+=1
    if t==2 :
        ecnt+=1

if cnt != 0 and cnt == ecnt:
    print(nomal + acnt-1)
else:
    print(nomal + min(acnt,bcnt))

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

Solution (Python):


n = int(input())

strings = []
for _ in range(n):
    strings.append(input())

ab = 0 
tail_a = 0 
head_b = 0 
both = 0
for s in strings:
    ab += s.count('AB')
    if s[-1] == 'A' and s[0] != 'B':
        tail_a += 1
    if s[0] == 'B' and s[-1] != 'A':
        head_b += 1
    if s[-1] == 'A' and s[0] == 'B':
        both += 1
ans = ab 
if both == 0:
    ans += min(tail_a, head_b)
elif tail_a + head_b > 0:
    ans += both + min(tail_a, head_b)
elif tail_a == 0 and head_b == 0:
    ans += max(both - 1, 0)
print(ans)

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

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

Solution (Python):


N = int(input().split()[0])
s_list = []
a_list = []
b_list = []
ab_list = []
ab_count = 0
for _ in range(N):
    s = input()
    s_list.append(s)
    ab_count += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        ab_list.append(s)
    elif s[0] == "B":
        b_list.append(s)
    elif s[-1] == "A":
        a_list.append(s)

if a_list:
    if ab_list:
        a_list.pop()
        ab_count += len(ab_list)
        if b_list:
            ab_count += 1
            b_list.pop()
        ab_count += max(min(len(a_list), len(b_list)), 0)
    else:
        ab_count += min(len(a_list), len(b_list))
elif b_list:
    ab_count += len(ab_list)
else:
    ab_count += max(len(ab_list) - 1, 0)

ans = ab_count
print(ans)

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

ba=0
_a=0
b_=0

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



if ba>0:
    ans+=(ba-1)
    if _a>0:
        _a-=1
        ans+=1
    if b_>0:
        b_-=1
        ans+=1

ans+=min(_a,b_)

print(ans)

Solution (Python):
import sys,os
from collections import defaultdict, deque
from math import ceil, floor
if sys.version_info[1] >= 5:
    from math import gcd
else:
    from fractions import gcd
sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = (lambda *something: print(*something)) if 'TERM_PROGRAM' in os.environ else lambda *x: 0
def main(given=sys.stdin.readline):
    input = lambda: given().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    MOD = 10**9+7

    N = II()
    S = [0]*N
    numAB = 0
    numA = 0
    numB = 0
    ans = 0
    for i in range(N):
        s = input()
        ans += s.count('AB')
        if s[-1] == 'A':
            if s[0] == 'B':
                numAB += 1
            else:
                numA += 1
        elif s[0] == 'B':
            numB += 1



    if numA > 0 and numAB > 0:
        numA -= 1
        numAB += 1
    
    
    if numB > 0 and numAB > 0:
        numB -= 1
        numAB += 1
    
    
    if numAB > 0:

        ans += numAB -1  + min(numA,numB)
    else:
        ans += min(numA,numB)
    
        
    print(ans)
if __name__ == '__main__':
    main()

Solution (Python):
import sys

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


def resolve():
    n = int(input())
    S = list(input() for _ in range(n))

    cnt_AB = 0
    cnt_A = 0
    cnt_B = 0
    res = 0
    for s in S:
        res += s.count("AB")
        if s[0] == "B" and s[-1] == "A":
            cnt_AB += 1
        elif s[0] == "B":
            cnt_B += 1
        elif s[-1] == "A":
            cnt_A += 1

    if cnt_A + cnt_B > 0:
        print(res + cnt_AB + min(cnt_A, cnt_B))
    else:
        print(res + max(0, cnt_AB - 1))


if __name__ == '__main__':
    resolve()

Solution (Python):
n=int(input())
a=0
b=0
ab=0
ans=0
for i in range(n):
    s=input()
    m=len(s)
    m-=len(s.replace("AB",""))
    m//=2
    ans+=m
    if s[0]=="B" and s[-1]=="A":
        ab+=1
    elif s[0]=="B":
        b+=1
    elif s[-1]=="A":
        a+=1

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

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline


def solve():
    N = int(rl())
    s = [input() for _ in range(N)]
    
    ans = 0
    cnt_a, cnt_b, cnt_ab = 0, 0, 0
    for si in s:
        ans += si.count('AB')
        if si[-1] == 'A' and si[0] == 'B':
            cnt_ab += 1
        elif si[-1] == 'A':
            cnt_a += 1
        elif si[0] == 'B':
            cnt_b += 1
    
    if cnt_ab == 0:
        ans += min(cnt_a, cnt_b)
    else:
        if 0 < cnt_a + cnt_b:
            ans += cnt_ab + min(cnt_a, cnt_b)
        else:
            ans += cnt_ab - 1
    print(ans)


if __name__ == '__main__':
    solve()

Solution (Python):
import math  
import bisect  
import queue  


if __name__ == '__main__':
    N = int(input())
    S = [input() for _ in range(N)]

    cnt = 0
    cnt_xa = 0
    cnt_bx = 0
    cnt_ba = 0
    for s in S:
        for i in range(0, len(s) - 1):
            if s[i] == 'A' and s[i + 1] == 'B':
                cnt += 1
        if 'B' != s[0] and 'A' == s[-1]:
            cnt_xa += 1
        if 'B' == s[0] and 'A' != s[-1]:
            cnt_bx += 1
        if 'B' == s[0] and 'A' == s[-1]:
            cnt_ba += 1

    if cnt_ba > 1:
        cnt += cnt_ba - 1
        cnt_ba = 1
    if (cnt_xa > 0 or cnt_bx > 0) and cnt_ba == 1:
        cnt += 1
    cnt += min(cnt_xa, cnt_bx)

    print(cnt)

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

for i in range(n):
    s[i] = input()
comb = [[0]*2 for i in range(2)]
    
al = 0
be = 0
ans = 0
for i in range(n):
    m = len(s[i])
    for j in range(m-1):
        if s[i][j] == "A" and s[i][j+1] == "B":
            ans += 1
    if s[i][0] == "B" and s[i][-1] == "A":
        comb[1][1] += 1
    elif s[i][0] == "B" and s[i][-1] != "A":
        comb[0][1] += 1
    elif s[i][0] != "B" and s[i][-1] == "A":
        comb[1][0] += 1
    else:
        comb[0][0] += 1
        
if comb[0][1] == 0 and comb[1][0] == 0:
    ans += max(0,comb[1][1] - 1)
elif comb[0][1] != 0 and comb[1][0] == 0:
    ans += comb[1][1]
elif comb[0][1] == 0 and comb[1][0] != 0:
    ans += comb[1][1]
else:
    ans += (comb[1][1] + 1 + min(comb[1][0]-1,comb[0][1]-1))
    
print(ans)

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

for i in range(n):
    s[i] = input()
comb = [[0]*2 for i in range(2)]
    
al = 0
be = 0
ans = 0
for i in range(n):
    m = len(s[i])
    for j in range(m-1):
        if s[i][j] == "A" and s[i][j+1] == "B":
            ans += 1
    if s[i][0] == "B" and s[i][-1] == "A":
        comb[1][1] += 1
    elif s[i][0] == "B" and s[i][-1] != "A":
        comb[0][1] += 1
    elif s[i][0] != "B" and s[i][-1] == "A":
        comb[1][0] += 1
    else:
        comb[0][0] += 1
        
if comb[0][1] == 0 and comb[1][0] == 0:
    ans += max(0,comb[1][1] - 1)
elif comb[0][1] != 0 and comb[1][0] == 0:
    ans += comb[1][1]
elif comb[0][1] == 0 and comb[1][0] != 0:
    ans += comb[1][1]
else:
    ans += (comb[1][1] + 1 + min(comb[1][0]-1,comb[0][1]-1))
    
print(ans)

Solution (Python):
N,*L = open(0).read().split()

ans = 0
a = 0
b = 0
c = 0
for s in L:
  for j in range(len(s)-1):
    if s[j]=='A' and s[j+1]=='B':
      ans += 1
  if s[-1]=='A' and s[0]=='B':
    c += 1
  elif s[-1]=='A':
    a += 1
  elif s[0]=='B':
    b += 1
if c!=0:
  if a+b>0:
    ans += c+min(a,b)
  else:
    ans += c-1
else:
  ans += min(a,b)
print(ans)

Solution (Python):

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

hoge  = "X"
PHASEA = 0
PHASEB = 1
phase  = 0
while ba != 0 or xa != 0 or bx != 0:
    if hoge[-1] == "X":
        if xa > 0:
            xa  -= 1
            hoge += "XA"
        elif ba > 0 :
            ba -= 1
            hoge += "BA"
        else:
            bx -= 1
            hoge += "BX"
    elif hoge[-1] == "A":
        if ba > 0 :
            ba -= 1
            hoge += "BA"
        elif bx > 0:
            bx  -= 1
            hoge += "BX"
        elif xa > 0:
            xa  -= 1
            hoge += "XA"

print(hoge.count("AB") + ans)

Solution (Python):
n = int(input())
a = 0
b = 0
ans = 0
ab = 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[-1] == "A":
    a += 1
  if s[0] == "B":
    b += 1
  if s[-1] == "A" and s[0] == "B":
    ab += 1
k = min([a, b])

if k == a and k == b and k == ab:
  k -= 1
if k == n:
  k -= 1
if k < 0:
  k = 0
ans += k
print(ans)

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

ab = 0
lastA = 0
onlylastA = 0
firstB = 0
onlyfirstB = 0
for s in S:
    ab += s.count('AB')
    if s[-1] == 'A' and s[0] != 'B':
        lastA += 1
        onlylastA += 1
    if s[0] == 'B' and s[-1] != 'A':
        firstB += 1
        onlyfirstB += 1
    if s[-1] == 'A' and s[0] == 'B':
        lastA += 1
        firstB += 1

ans = ab + min(lastA,firstB)
if lastA != 0 and onlylastA == 0 and onlyfirstB == 0:
    ans = max(ans-1,0)
print(ans)

Solution (Python):
N = int(input())
s = [(input()) for _ in range(N)]
ans = 0
a_cnt = 0
b_cnt = 0
ab_cnt = 0
for i in range(N):
  if s[i][0] == 'B' and s[i][-1] == 'A':
    ab_cnt += 1
  elif s[i][0] == 'B':
    b_cnt += 1
  elif s[i][-1] == 'A':
    a_cnt += 1
  for j in range(len(s[i])-1):
    if s[i][j] + s[i][j+1] == 'AB':
      ans += 1
if ab_cnt == 0:
  print(ans + min(a_cnt, b_cnt))
else:
  ans += ab_cnt - 1 
  if a_cnt > 0:
    ans += 1
    a_cnt -= 1
  if b_cnt > 0:
    ans += 1
    b_cnt -= 1
  ans += min(a_cnt, b_cnt)
  print(ans)

Solution (Python):

if False:
    B=[int(i) for i in input().split()]
    N=int(input())
    rep={}
    for i,b in enumerate(B):
        rep[str(b)]=str(i)
    
    ans=[]
    for _ in range(N):
        a=input()
        num=''
        for d in a:
            num+=rep[d]
        ans.append((a,int(num)))
    ans.sort(key=lambda x: x[1])
    for i in range(N): print(ans[i][0])


if False:
    N=int(input())
    S=[tuple(map(int,input().split('/'))) for _ in range(N)]
    if len(S)>=366: print(366)
    elif N==0: print(2)
    else:
        cal=[[] for m in range(12)]
        day=6 
        for m in range(12):
            if m+1==2: e=29
            elif m+1 in (4,6,9,11): e=30
            else: e=31
            for d in range(1,e+1):
                cal[m].append([d,day,day in (5,6)])
                day=(day+1)%7
        for m,d in S:
            m-=1
            d-=1
            while cal[m][d][2]:
                if d+1<len(cal[m]): d+=1
                else:
                    m+=1
                    m%=12
                    d=0
                if (m,d)==(11,30): break
            cal[m][d][2]=True
        ans=-1
        cnt=0
        for m in range(12):
            for d in range(len(cal[m])):
                if cal[m][d][2]:
                    cnt+=1
                else:
                    ans=max(ans,cnt)
                    cnt=0
        ans=max(ans,cnt)
        print(ans)
        


if False:
    N=int(input())
    H=[int(input()) for _ in range(N)]
    if N==1: print(1); exit()
    ans=0
    cnt=2
    prev=1 if H[0]<H[1] else 0 
    for i in range(1,N-1):
        tmp=1 if H[i]<H[i+1] else 0
        if prev<tmp:
            ans=max(ans,cnt)
            cnt=2
        else:
            cnt+=1
        prev=tmp
    ans=max(ans,cnt)
    print(ans)


if True:
    N=int(input())
    S=[input() for _ in range(N)]
    ans=0
    cnt={'BA':0,'BX':0,'XA':0}
    for s in S: ans+=s.count('AB')
    for s in S:
        l=s[0]
        r=s[-1]
        if l=='B' and r=='A': cnt[l+r]+=1
        elif l=='B': cnt[l+'X']+=1
        elif r=='A': cnt['X'+r]+=1 
    if cnt['BA']:
        ans+=cnt['BA']-1
        if cnt['BX'] and cnt['XA']:
            ans+=min(cnt['BX']-1,cnt['XA']-1)+2
        else:
            ans+=int(bool(cnt['BX']))+int(bool(cnt['XA']))
    else:
        ans+=min(cnt['BX'],cnt['XA'])
    print(ans)