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())
s = []
c = 0
check = [0,0,0]
for i in range(n):
  s.append(input())
  c+=s[i].count("AB")
  if s[i][0] == 'B' and s[i][-1] == 'A':
    check[0]+=1
  elif s[i][0] == 'B':
    check[1]+=1
  elif s[i][-1] == 'A':
    check[2]+=1
    
if check[0] == 0:
  c+=min(check[1],check[2])
elif check[1] + check[2] == 0:
  c+=check[0]-1
else:
  c+=check[0]+min(check[1],check[2])
print(c)

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

s=[]
res = 0
tmp = 0
eA=0
sB=0
eAsB=0
for i in range(n):
	s.append(input())
	tmp = s[i].count("AB")
	if tmp != 0:
		res += tmp
	if s[i][0]=="B" and s[i][-1]=="A":
		eAsB += 1
	elif s[i][-1]=="A":
		eA += 1
	elif s[i][0]=="B":
		sB += 1

if eAsB != 0:
	if eA < sB:
		res += eA+1
	elif eA == 0 and sB == 0:
		res += 0
	else:
		res += sB+1
else:
	if eA < sB:
		res += eA
	else:
		res += sB

if eAsB > 1:	
	res += eAsB-1

print(res)

Solution (Python):
n=int(input())
ans=0;BA,BB,AA=0,0,0
for i in range(n):
  s=input()
  for i in range(len(s)-1):
    if s[i]+s[i+1]=="AB":ans+=1
  if s[0]+s[-1]=="BA":BA+=1
  elif s[-1]=="A":AA+=1
  elif s[0]=="B":BB+=1
if BA==0:print(ans+min(AA,BB))
else:
  ans+=BA-1
  BA=1
  if AA!=0:AA-=1;ans+=1
  if BB!=0:BB-=1;ans+=1
  print(ans+min(AA,BB))

Solution (Python):
n=int(input())
s=[input() for _ in range(n)]
isFinishA=[s[i][-1]=='A' for i in range(n)]
isStartB=[s[i][0]=='B' for i in range(n)]
ans=0
for si in s:
    wasA=False
    for sij in si:
        if sij=='B':
            if wasA:
                ans+=1
        wasA=(sij=='A')
cnt=[isFinishA.count(True),isStartB.count(True)]
ans+=min(cnt)
fromBtoA=0
for i in range(n):
    if isFinishA[i] and isStartB[i]:
        fromBtoA+=1

if cnt[0]==cnt[1]==fromBtoA:
    if cnt[0]!=0:
        ans-=1
print(ans)

Solution (Python):
N = int(input())
cnt = 0
abcount = 0
acount = 0
bcount = 0

for i in range(N):
	s = input()
	cnt += s.count('AB')
	if s.startswith('B') and s.endswith('A'):
		abcount += 1
	if s.startswith('B'):
		bcount += 1
	if s.endswith('A'):
		acount += 1

if acount == 0 and bcount == 0 and abcount == 0:
	print(cnt)
elif abcount == acount and abcount == bcount:
	print(cnt + abcount -1)
else:
	print(cnt + min(acount, bcount))

Solution (Python):
from collections import Counter
from collections import deque
from functools import reduce
from pprint import pprint

import bisect
import copy
import fractions
import math
import random
import sys
import time
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def MI(): return map(int, sys.stdin.readline().split())
def II(): return int(sys.stdin.readline())
def IS(): return input()
def C(x): return Counter(x)
def GCD_LIST(numbers):
    return reduce(fractions.gcd, numbers)
def LCM_LIST(numbers):
    return reduce(LCM, numbers)
def LCM(m, n):
    return (m * n // fractions.gcd(m, n))
def unite(x, y):
    
    x = root(x)
    y = root(y)
    if x == y:
        return
    
    node[x] = y
def same(x,y): return bool(root(x) == root(y))
def root(x):
    if node[x] == x:  
        return x
    else:
        node[x] = root(node[x])  
        return node[x]
def dfs(v):
    
    visited[v] = True
    for v2 in range(n):
        if graph[v][v2] == False:  
            continue
        if visited[v2] == True:  
            continue
        dfs(v2)

n = II()
s = [IS() for _ in range(n)]
cnt = 0
sentou_b = 0
ushiro_a = 0
ab = 0
for i in s:
    cnt += i.count('AB')
    if i[0] == 'B' and i[-1] == 'A':
        ab += 1
    else:
        if i[0] == 'B':
            sentou_b += 1
        if i[-1] == 'A':
            ushiro_a += 1
if ab == 0:
    print(cnt+min(sentou_b, ushiro_a))
elif ab > 0:
    if sentou_b + ushiro_a > 0:
        print(cnt+ab+min(sentou_b, ushiro_a))
    elif sentou_b + ushiro_a == 0:
        print(cnt+ab-1)

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

Bset = set()
Aset = set()
ans = 0
for i in range(n):
    if s[i][0] == "B":
        Bset.add(i)
    if s[i][-1] == "A":
        Aset.add(i)
    for j in range(1, len(s[i])):
        if s[i][j - 1] == "A" and s[i][j] == "B":
            ans += 1

Bli = list(Bset)
Ali = list(Aset)
ans += min(len(Bli), len(Ali))
if Bset == Aset and Bset != set():
    ans -= 1
print(ans)

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

cnt = 0
b_start = 0
a_end = 0
b_start_and_a_end = 0

for i in range(N):
    s = input()
    cnt += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        b_start_and_a_end += 1
    elif s[0] == 'B':
        b_start += 1
    elif s[-1] == 'A':
        a_end += 1

cnt += min(a_end,b_start)

if b_start == a_end == 0:
    cnt += max(0,b_start_and_a_end-1)
else:
    cnt += b_start_and_a_end

print(cnt)

Solution (Python):
N = int(input())
headB=0
tailA=0 
both = 0
ans = 0
for j in range(N):
    t = input()
    if t[0] == "B":
        if t[-1] == "A":
            both += 1
        else:
            headB += 1
    elif t[-1] == "A":
        tailA += 1
    ans += t.count("AB")
if both > 0:
    ans += both - 1
    if tailA > 0 or headB > 0:
        ans += 1
ans += min(tailA,headB)
print(ans)

Solution (Python):
import re
aflag = 0
bflag = 0
cnt = 0
cntna = 0

N = int(input())
for i in range(N):
    s = input()
    if s[-1:] == "A":
        aflag += 1
    if s[:1] == "B":
        bflag += 1
    if re.search("AB", s):
        cnt += 1
    if re.search("AB.*AB", s):
        cnt += 1
    if re.search("AB.*AB.*AB", s):
        cnt += 1
    if re.search("AB.*AB.*AB.*AB", s):
        cnt += 1
    if re.search("ABABABABAB", s):
        cnt += 1
    if s[-1:]=="A" and s[:1]=="B":
        cntna +=1

cnt += min(aflag, bflag)
if min(aflag,bflag) == N:
    cnt -= 1
if cntna == min(aflag, bflag) and aflag == bflag and aflag != 0 and bflag != 0:
    cnt -= 1
if aflag == bflag == N:
    cnt += 1
print(cnt)

Solution (Python):
import sys
sys.setrecursionlimit(1000000)

def f(a,b,ba):
  if a>0 and ba>0:
    return 1 + f(a,b,ba-1)
  elif a>0 and b>0:
    return 1+ f(a-1,b-1,ba)
  elif ba>1:
    return 1 + f(a+1,b,ba-2)
  elif ba>0 and b>0:
    return 1 + f(a,b-1,ba-1)

  return 0

N=int(input())
a=[]
b=[]

stA=0
stB=0
stBA=0

ans=0
for x in range(N):
  z=input()
  buf=z.count("AB")
  b.append((z[0],z[-1],buf))
  ans+=buf

for z in b:
  if z[0]=="B" and z[1]=="A":
    stBA+=1
  elif z[0]=="B":
    stB+=1
  elif z[1]=="A":
    stA+=1

ans=ans+f(stA,stB,stBA)
print(ans)

Solution (Python):
N = int(input())
a = [str(input()) for i in range(N)]
cnt = 0
tBeA = 0
tBeNA = 0
tNBeA = 0
for i in range(N):
    flag = False
    if a[i][0] == "B":
        if a[i][-1] == "A":
            tBeA += 1
        else:
            tBeNA += 1
    else:
        if a[i][-1] == "A":
            tNBeA += 1

    for j in range(len(a[i])):
        
        if a[i][j] == "B" and flag:
            cnt += 1
        flag = False

        if a[i][j] == "A":
            flag = True

print(
    cnt + min(tBeNA, tNBeA) if tBeA == 0 else cnt + min(tBeNA, tNBeA) + tBeA if tNBeA + tBeNA > 0 else cnt + min(tBeNA,
                                                                                                                 tNBeA) + tBeA - 1)

Solution (Python):



def main():
    n = int(input())
    s = [input() for _ in range(n)]
    ans = 0
    back_a_count = 0
    front_b_count = 0
    front_b_back_a_count = 0

    for si in s:
        if si[0] == 'B':
            front_b_count += 1
        if si[-1] == 'A':
            back_a_count += 1
        if si[0] == 'B' and si[-1] == 'A':
            front_b_back_a_count += 1

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

    ans += min(back_a_count, front_b_count)

    
    
    if front_b_count == back_a_count == front_b_back_a_count:
        if front_b_back_a_count > 0:
            ans -= 1

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):



def main():
    n = int(input())
    s = [input() for _ in range(n)]
    ans = 0
    back_a_count = 0
    front_b_count = 0
    front_b_back_a_count = 0

    for si in s:
        if si[0] == 'B':
            front_b_count += 1
        if si[-1] == 'A':
            back_a_count += 1
        if si[0] == 'B' and si[-1] == 'A':
            front_b_back_a_count += 1

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

    ans += min(back_a_count, front_b_count)

    
    
    if front_b_count == back_a_count == front_b_back_a_count:
        if front_b_back_a_count > 0:
            ans -= 1

    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
def c(strs):
    count = 0
    count_a = 0
    count_b = 0
    flag = 1
    for s in strs:
        count += s.count('AB')
        if s[0]=='B' and s[-1]=='A':
            count_a += 1
            count_b += 1
        elif s[0]=='B':
            count_b += 1
            flag = 0
        elif s[-1]=='A':
            count_a += 1
            flag = 0
    if count_a:
        return count + min(count_a,count_b) - flag
    return count


if __name__=='__main__':
    n = int(input())
    s = []
    for _ in range(n):
        s.append(input())
    print(c(s))

Solution (Python):
def c_ab_substrings(N, S):
    """
    N個の文字列を好きな順序で並べたあと、連結して1つの文字列を作る。
    作った文字列に 'AB' という部分文字列が含まれる個数として
    ありうる値のうち最大のものを求めよ。
    """

    num_start_b_end_a = 0
    num_start_b_not_end_a = 0
    num_not_start_b_end_a = 0
    ans = 0
    for s in S:
        if s[0] == 'B' and s[-1] == 'A':
            num_start_b_end_a += 1
        if s[0] == 'B' and s[-1] != 'A':
            num_start_b_not_end_a += 1
        if s[0] != 'B' and s[-1] == 'A':
            num_not_start_b_end_a += 1
        ans += s.count('AB')
    if num_start_b_end_a == 0:
        
        ans += min(num_start_b_not_end_a, num_not_start_b_end_a)
    else:
        
        
        if num_start_b_not_end_a + num_not_start_b_end_a > 0:
            ans += num_start_b_end_a + min(num_start_b_not_end_a, num_not_start_b_end_a)
        else:
            ans += num_start_b_end_a - 1
    return ans

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

Solution (Python):
headB = 0
tailA = 0
both = 0
c = 0
for i in range(int(input())):
    t = input()
    if t[0] =='B' and t[-1]=='A':
        both+=1
    elif t[0] == 'B':
        headB+=1
    elif t[-1] == 'A':
        tailA +=1
    c+=t.count('AB')
if both>0:
    if tailA+headB>0:
        if tailA:
            c+=1
            tailA-=1
        if headB:
            c+=1
            headB-=1
        c+=min(headB,tailA)
        c+=both-1
    else:
        c+=both-1
else:
    c+=min(tailA,headB)
print(c)

Solution (Python):
n = int(input())
S = []
result = 0
A_count = 0
B_count = 0
BA_count = 0

for i in range(n):
    Si = str(input())
    S.append(Si)

for i in range(n):
    Si = S[i]
    result += Si.count("AB")
    if Si[0] == "B" and Si[-1] != "A":
        B_count += 1
    if Si[0] != "B" and Si[-1] == "A":
        A_count += 1
    if Si[0] == "B" and Si[-1] == "A":
        BA_count += 1 

if BA_count >= 2:
    result += (BA_count - 1)

if BA_count >= 1:
    if B_count >= 1:
        result += 1
        B_count -= 1
    if A_count >= 1:
        result += 1
        A_count -= 1

if B_count >= 1 and A_count >= 1:
    result += min(B_count, A_count)

print(result)

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

contained = sum([s.count('AB') for s in ss])
B_hoge = sum([1 for s in ss if s[0]=='B'])
hoge_A = sum([1 for s in ss if s[-1]=='A'])
B_hoge_A = sum([1 for s in ss if s[0]=='B' and s[-1]=='A'])

B_hoge -= B_hoge_A
hoge_A -= B_hoge_A

ans = contained
if B_hoge_A==0:
    ans += min(B_hoge, hoge_A)
elif B_hoge + hoge_A > 0:
    ans += B_hoge_A + min(B_hoge, hoge_A)
else:
    ans += B_hoge_A -1
print(ans)

Solution (Python):

n = int(input())
s = [input() for _ in range(n)]
a = 0
b = 0
ab = 0
ans = 0
for x in s:
    if x[0] == 'B':
        if x[len(x)-1] == 'A':
            ab += 1
        else:
            b += 1
    elif x[len(x)-1] == 'A':
        a += 1
    ans += x.count('AB')
if ab == 0:
    print(ans+min(a,b))
else:
    if a + b > 0:
        print(ans+ab+min(a,b))
    else:
        print(ans+ab-1)

Solution (Python):
N = int(input())
end_a = 0
start_b = 0
a_and_b = 0
count = 0
for i in range(N):
    s = input()
    count += s.count('AB')
    s.replace('AB', '')
    if s[0] == 'B' and s[-1] == 'A':
        a_and_b += 1
    elif s[0] == 'B':
        start_b += 1
    elif s[-1] == 'A':
        end_a += 1


if a_and_b == 0:
    print(count + min(end_a, start_b))
elif end_a + start_b == 0:
    print(count + a_and_b - 1)
else:
    print(count + a_and_b + min(end_a, start_b))

Solution (Python):
import sys

input = sys.stdin.readline

N = int(input())
A, B, AB = 'A', 'B', 'AB'
endA, startB, startB_endA = 0, 0, 0
ans = 0

for _ in range(N):
    S = input().rstrip()

    if S[0] == B:
        startB += 1

        if S[-1] == A:
            startB -= 1
            startB_endA += 1

    elif S[-1] == A:
        endA += 1
    

    for i in range(1,len(S)):
        if S[i-1] + S[i] == AB:
            ans += 1


if startB_endA == 0:
    ans += min(endA, startB)

elif endA == 0 and startB == 0:
    ans += max(0, startB_endA - 1)

else:
    ans += startB_endA + min(endA, startB)

print(ans)

Solution (Python):
n = int(input())
 
g1 = []
g2 = []
g3 = []
 
cnt = 0
 
for i in range(n):
    s = input()
    cnt += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        g3.append(s)
    elif s[0] == "B":
        g1.append(s)
    elif s[-1] == "A":
        g2.append(s)
        
a = len(g1)
b = len(g2)
c = len(g3)
 
if a == b:
    if a == c:
        cnt += c * 2
    elif a > c:
        cnt += c
        cnt += a
    elif a < c:
        if a == 0:
            cnt += c - 1
        else:
            cnt += a
            cnt += c
elif a > b:
    cnt += b
    cnt += c
elif b > a:
    cnt += a
    cnt += c
 
print(cnt)

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

b = 0
a = 0
ba = 0
ans = 0

for i in range(n):
    s.append(input())
    ans += s[i].count('AB')
    if s[i].startswith('B') and s[i].endswith('A'):
        ba += 1
    elif s[i].startswith('B'):
        b += 1
    elif s[i].endswith('A'):
        a += 1

if ba == 0:
    ans += min(a, b)
elif ba != 0 and b + a > 0:
    ans += ba + min(a, b)
elif ba != 0 and b + a == 0:
    ans += ba - 1

print(ans)

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

a, b, ba, ab = 0, 0, 0, 0
for ss in s:
    ab += ss.count('AB')

    bl_a = ss[-1] == 'A'
    bl_b = ss[0] == 'B'
    if bl_a:
        if bl_b:
            ba += 1
        else:
            a += 1
    else:
        if bl_b:
            b += 1
        else:
            pass

ans = 0
ans += ab

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)

"""
...AB...
ab

B...A
ba

...A
a

B...
b
"""

Solution (Python):
N = int(input())
s = [input() for i in range(N)]
flg = 1
cnt = 0
ca = 0
cb = 0
for i in range(N):
  if s[i][0] == 'B' and s[i][-1] == 'A':
    ca += 1
    cb += 1
  elif s[i][0] == 'B':
    cb += 1
    flg = 0
  elif s[i][-1] == 'A':
    ca += 1
    flg = 0
  cnt += s[i].count('AB')

if  min(ca, cb) > 0:
  cnt += min(ca, cb) - flg

print (cnt)

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

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

Solution (Python):
n = int(input())
s_array = [input() for x in range(n)]
last_a = 0
reversible = 0
start_b = 0
flag = False
for s in s_array:
    if s[-1] == "A" and s[0] != "B":
        last_a += 1
    elif s[0] == "B" and s[-1] != "A":
        start_b += 1
    elif s[0] == "B" and s[-1] == "A":
        reversible += 1
    else:
        flag = True
res = 0
for s in s_array:
    res += s.count("AB")

if start_b > last_a or flag:
    tmp = 0
else:
    tmp = 1

if n == 1:
    print(res)
elif reversible == 0:
    print(res + min(last_a, start_b))
elif last_a == 0 and start_b == 0:
    print(res + reversible - 1)
elif last_a == 0 or start_b == 0:
    print(res + min(last_a, start_b) + reversible)
else:
    print(res + min(last_a, start_b) + reversible)

Solution (Python):



N = int(input())
S = [input() for i in range(N)]
ab = x_a = b_x = b_a = 0
for s in S:
    ab += s.count('AB')
    if s[-1]=='A' and s[0]=='B':
        b_a += 1
    elif s[-1]=='A':
        x_a += 1
    elif s[0]=='B':
        b_x += 1
        
ans = ab


if b_a:
    
    ans += b_a - 1
    if x_a:
        
        ans += 1
        
        x_a -= 1
    if b_x:
        ans += 1
        b_x -= 1
        

ans += min(x_a, b_x)
print(ans)

Solution (Python):
n = int(input())
s = [input() for i in range(n)]
count = 0
count_a = 0
count_b = 0
count_ab = 0
for i in range(n):
    count += s[i].count("AB")
    if s[i][-1] == "A" and s[i][0] != "B":
        count_a += 1
    if s[i][0] == "B" and s[i][-1] != "A":
        count_b += 1
    if s[i][0] == "B" and s[i][-1] == "A":
        count_ab += 1


if count_ab == 0:
    print(count+min([count_a,count_b]))
else:
    if count_a + count_b == 0:
        print(count+count_ab-1)
    else:
        print(count+min([count_a,count_b])+count_ab)

Solution (Python):
import re

N = int(input())

startB = 0
stopA = 0
BtoA = 0
AB = 0

for i in range(N):
    s = input()
    if s.startswith("B") and s.endswith("A"):
        BtoA += 1
    elif s.startswith("B"):
        startB += 1
    elif s.endswith("A"):
        stopA += 1
    
    AB += len(re.findall("AB", s))


if BtoA == 0:
    ans = AB + min(startB, stopA)
elif startB + stopA > 0:
    ans = AB + min(startB, stopA) + BtoA
else:
    ans = AB + min(startB, stopA) + BtoA - 1
print(ans)

Solution (Python):
import sys 
import re

input()
bsn = 0
aen = 0
cen = 0
t = 0
for line in sys.stdin:
    st = line.strip()
    t += st.count("AB")
    if st[0] == "B" and st[-1] == "A":
        cen += 1
    elif st[0] == "B":
        bsn += 1
    elif st[-1] == "A":
        aen += 1

if aen != 0:
    if bsn != 0:
        if cen != 0:
            x = min(bsn-1, aen-1)
            print(t+cen+1+x)
        else:
            x = min(bsn, aen)
            print(t+x)
    else:
        print(t+cen)
else:
    if bsn != 0:
        print(t+cen)
    else:
        if cen != 0:
            print(t+cen-1)
        else:
            print(t)

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

count = 0
ba = 0
b = 0
a = 0

for _ in range(N):
    s = input()
    if s[0] == "B":
        if s[-1] == "A":
            ba += 1
        else:
            b += 1
    elif s[-1] == "A":
        a += 1

    n = len(s)
    for i in range(n-1):
        if s[i] == "A" and s[i+1] == "B":
            count += 1


count += max(ba-1, 0)

if ba >= 1:
    if a >= 1 and b >= 1:
        count += 2
        a -= 1
        b -= 1
    elif a > b:
        count += 1
        a -= 1
    elif b > a:
        count += 1
        b -= 1


count += min(a, b)        

print(count)

Solution (Python):



from collections import deque
import heapq
import math
import bisect


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

    a = b = ab = 0
    ans = 0
    for s in S:
        n = len(s)
        for j in range(n-1):
            if s[j] == "A" and s[j+1] == "B":
                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:
        print(ans+min(a, b))
    elif a == 0 and b == 0:
        print(ans+ab-1)
    else:
        print(ans+ab+min(a, b))


if __name__ == '__main__':
    main()

Solution (Python):
N=int(input())
s=[]
for i in range(N):
	s.append(input())
count=0

target = "AB"
for i in range(N):
	index = -1
	while True:
		index = s[i].find(target, index + 1)
		if index == -1:
			break
		count += 1







a=0
b=0
ba=0


for i in range(N):
	if s[i][-1]=="A" and s[i][0]=="B":
		ba+=1
	elif s[i][-1] == "A" and s[i][0] != "B":
		a+=1
	elif s[i][-1] != "A" and s[i][0] == "B":
		b+=1



"""
one=min(a,b)
two=0
if ba>0:
	two=ba-1

	if abs(a-b)>0:
		two=ba-1+1
print(one+two+count)
"""

if ba==0:
	count+=min(a,b)
else:
	if a==0 and b==0:
		count += (ba - 1)
	elif a == 0 or b == 0:
		count += ba
	else:
		count +=(ba + min(a,b))
		
		
		
		







print(count)

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


cnt_ab = sum([s.count('AB') for s in S])


cnt_b_a = sum([(s[0] == 'B') and (s[-1] == 'A') for s in S])


cnt_b_na = sum([(s[0] == 'B') and (s[-1] != 'A') for s in S])


cnt_nb_a = sum([(s[0] != 'B') and (s[-1] == 'A') for s in S])

count = cnt_ab
if (cnt_b_a == 0): 
    count += min(cnt_b_na, cnt_nb_a)
elif (cnt_b_na + cnt_nb_a == 0): 
    count += (cnt_b_a - 1)
else:
    count += (cnt_b_a + min(cnt_b_na, cnt_nb_a))
print(count)

Solution (Python):

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


a = sum(t[0] != 'B' and t[-1] == 'A' for t in s)
b = sum(t[0] == 'B' and t[-1] != 'A' for t in s)
ba = sum(t[0] == 'B' and t[-1] == 'A' for t in s)





ans = (
    sum(t.count('AB') for t in s) +
    (
        ba if a > 0 else
        max(0, ba - 1)
    ) +
    (
        min(1, b) if a == 0 and ba > 0 else
        min(a, b)
    )
)


print(ans)

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

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

if cntab==0:
  ans=cnt+min(cnta,cntb)
else:
  ans=cnt+cntab+min(cnta,cntb)

if cnta==0 and cntb==0:
  if cntab > 0:
    ans=cnt+cntab-1
  else:
    ans=cnt
print(ans)

Solution (Python):
N = int(input())
ans = 0
pattern = {"BA":0,"A":0,"B":0}
for i in range(N):
    s = input()
    ans += s.count("AB")
    if(s[0]=="B" and s[-1]=="A"):
        pattern["BA"]+=1
    elif(s[-1]=="A"):
        pattern["A"]+=1
    elif(s[0]=="B"):
        pattern["B"]+=1

if pattern["BA"]==0:
    ans += min(pattern["A"], pattern["B"])
else:
    ans += pattern["BA"]-1
    ans += pattern["A"]>0
    ans += pattern["B"]>0
    ans += max(0, min(pattern["A"]-1, pattern["B"]-1))
print(ans)

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

ab_list = []
for _ in range(N):
    ab_list.append(input())
    

ab_cnt = 0
a_cnt = 0
b_cnt = 0
in_cnt = 0

for tmp_list in ab_list:
    
    in_cnt += tmp_list.count('AB')
    
    
    if tmp_list.startswith('B') and tmp_list.endswith('A'):
        ab_cnt += 1
        
    
    elif tmp_list.endswith('A'):
        a_cnt += 1
    
    
    elif tmp_list.startswith('B'):
        b_cnt += 1
        

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


print(ans)

Solution (Python):
import re
N = int(input())
s = [input() for i in range(N)]

count_AB = 0
count_A = set()
count_B = set()

for i in range(N):
    _s = s[i]
    if _s[0] == "B":
        count_B.add(i)
    if _s[len(_s)-1] == "A":
        count_A.add(i)
    count_AB += len(re.findall("AB", _s))


inter = (count_A & count_B)
count_max = max(len(count_A), len(count_B))
count_min = min(len(count_A), len(count_B))
cnt = 0
if len(inter) == 0:
    cnt = count_min
elif len(inter) == count_max:
    cnt = len(inter) - 1
else:
    cnt = count_min


print(count_AB + cnt)

Solution (Python):
from sys import stdin
n = int(stdin.readline().rstrip())
ans=0
ba=0
bx=0
xa=0
for i in range(n):
  s = stdin.readline().rstrip()
  for j in range(len(s)-1):
    if s[j] == 'A' and s[j+1] == 'B':
      ans +=1
  if( s[0] == 'B' and s[-1] == 'A' ):
    ba +=1
  elif s[0] == 'B':
    bx +=1
  elif s[-1] == 'A':
    xa +=1

ans += min(xa,bx)
if ba>0:
  ans += (ba-1)
  if (xa+bx)!=0:
    ans += 1

print(ans)

Solution (Python):
N = int(input())
S = [input() for _ in range(N)]
ans = 0
ba = b = a = 0
for s in S:
    ans += s.count('AB')
    if s[0] + s[-1] == 'BA':
        ba += 1
    elif s[0] == 'B':
        b += 1
    elif s[-1] == 'A':
        a += 1
if ba == 0:
    ans += min([b, a])
elif b or a:
    ans += ba + min([b, a])
else:
    ans += ba + min([b, a]) - 1
print(ans)

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

Solution (Python):
n=int(input())
S=[list(input())for i in range(n)]
A_cnt=0
B_cnt=0
AB_cnt=0
for s in S:
        if s[0]=="B" and s[-1]=="A":
                AB_cnt+=1
        elif s[-1]=="A":
                A_cnt+=1
        elif s[0]=="B":
                B_cnt+=1
cnt=0
for i in range(n):
        for j in range(len(S[i])-1):
                if S[i][j]=="A" and S[i][j+1]=="B":
                        cnt+=1
if A_cnt==B_cnt==0 and 0<AB_cnt:
        print(AB_cnt-1+cnt)
else:
        print(cnt+min(A_cnt+AB_cnt,B_cnt+AB_cnt))

Solution (Python):
n=int(input())
S=[list(input())for i in range(n)]
A_cnt=0
B_cnt=0
AB_cnt=0
for s in S:
        if s[0]=="B" and s[-1]=="A":
                AB_cnt+=1
        elif s[-1]=="A":
                A_cnt+=1
        elif s[0]=="B":
                B_cnt+=1

cnt=0
for i in range(n):
        S[i].append("T")
        for j in range(len(S[i])):
                if S[i][j]=="A" and S[i][j+1]=="B":
                        cnt+=1
if A_cnt==B_cnt==0 and 0<AB_cnt:
        print(AB_cnt-1+cnt)
else:
        print(cnt+min(A_cnt+AB_cnt,B_cnt+AB_cnt))

Solution (Python):

"""
Created on Sun May 12 12:43:59 2019

@author: Yamazaki Kenichi
"""

N = int(input())
S = [input() for i in range(N)]

ans = 0
firstB, lastA, u = 0, 0, 0
for s in S:
    flg = False
    for c in s:
        if flg and c == "B":
            ans += 1
        flg = False
        if c == 'A':
            flg = True
    if s[0] == 'B':
        firstB += 1
    if s[-1] == 'A':
        lastA += 1
    if s[0] == 'B' and s[-1] == 'A':
        u += 1
ans += min(firstB,lastA)
ans -= 1 if u == firstB and u == lastA and u != 0 else 0
print(ans)

Solution (Python):
N = int(input())
topb = 0
taila = 0
both = 0
cnt = 0
for _ in range(N):
    s = input()
    cnt +=s.count("AB")

    if s[0] == "B" and s[-1] == "A":
        both += 1
    elif s[0] == "B":
        topb += 1
    elif s[-1] == "A":
        taila += 1
add_cnt = 0
if taila == 0 and topb == 0 and both >0:
    add_cnt = both -1
else:
    add_cnt = min(taila + both,topb + both)

print(cnt + add_cnt)

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

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

Solution (Python):

N = int(input())



count = 0
a, b, ba = 0, 0, 0
for i in range(N):
    s = input().rstrip()
    count += s.count("AB")

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




if ba > 1:
    count += ba - 1
    ba = 1

if a + b > 0:
    
    count += min(a,b) + ba
print(count)

Solution (Python):
N=input()

ans=0
r_a_cnt=0
l_b_cnt=0
both=0

for _ in range(N):
	s=raw_input()
	if s[0]=="B" and s[-1]=="A": both+=1
	elif s[0]=="B": l_b_cnt+=1
	elif s[-1]=="A": r_a_cnt+=1

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

if l_b_cnt==r_a_cnt==0 and both>0:
	ans+=both-1
else:
	ans+=min( l_b_cnt+both , r_a_cnt+both)

print ans

Solution (Python):
N=int(input())
countab,counta,countb,count=0,0,0,0
for i in range(N):
	s=input()
	if (s[0]=='B')&(s[-1]!='A'):
		countb+=1
	if (s[-1]=='A')&(s[0]!='B'):
		counta+=1
	if (s[0]=='B')&(s[-1]=='A'):
		count+=1
	countab+=s.count('AB')
if count==0: print(min(counta,countb)+countab)
elif counta+countb==0: print(count-1+countab)
else: print(min(counta,countb)+countab+count)

Solution (Python):
from collections import defaultdict
import math


def kari():
    map(int, input().split())
    list(map(int, input().split()))
    math.ceil()

def main():
    num = int(input())
    data = [input() for i in range(num)]
    count = 0
    for i in range(num):
        count += data[i].count('AB')

    count_a, count_b, ryouhou = 0, 0, 0
    for i in range(num):
        if data[i][0] == 'B' and data[i][-1] == 'A':
            ryouhou += 1
        elif data[i][0] == 'B':
            count_b += 1
        elif data[i][-1] == 'A':
            count_a += 1

    

    if count_a > 0 and count_b > 0:
        count_a -= 1
        count_b -= 1
        count += ryouhou + 1 + min(count_a, count_b)
    elif count_a > 0 or count_b > 0:
        count += ryouhou
    else:
        count += max(0, ryouhou - 1)


    
    print(count)


if __name__ == '__main__':
    main()

Solution (Python):


"""
Created on Fri Mar  1 19:29:34 2019

@author: nakamuratakayuki
"""
N = int(input())
S = []
for i in range(N):
    S.append(input())

m = 0
f = 0
b = 0
t = 0
for s in S:
    if s.startswith('B'):
        m += 1
    if s.endswith('A'):
        f += 1
    if s.startswith('B')*s.endswith('A'):
        m -= 1
        f -= 1
        b += 1
    t += s.count('AB')
if f == 0 and m == 0:
    b -= 1
ans = min(f,m)+max(b,0)+t

print(max(ans,0))

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

cnt = 0
for i in range(n):
    cnt += s[i].count("AB")
cnt_a = 0
cnt_b = 0
cnt_ab = 0
for i in range(n):
    len_s = len(s[i])
    if s[i][0] == "B" and s[i][len_s - 1] == "A":
        cnt_ab += 1
    elif s[i][len_s - 1] == "A":
        cnt_a += 1
    elif s[i][0] == "B":
        cnt_b += 1
if cnt_a == cnt_b == 0 and cnt_ab > 0:
    print(cnt + cnt_ab - 1)
else:
    print(cnt + min(cnt_a, cnt_b) + cnt_ab)

Solution (Python):
n=int(input())
c=0
d=0
a=0
k=0
for i in range(n):
    s=input()
    if "AB" in s:
        c+=s.count("AB")
    if s[0]=="B" and s[len(s)-1]=="A":
        d+=1
    if s[0]=="B" and s[len(s)-1]!="A":
        a+=1
    if s[len(s)-1]=="A" and s[0]!="B":
        k+=1
if a+k==0:
    print(max(c+d-1,c))
elif a+k>0:
    print(c+min(d+a,d+k))
else:
    print(c+min(a,k))