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 = [input() for i in range(n)]

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




while 1:
    if BA == 0 or A == B:
        break
    if A >= B:
        B += 1
    else:
        A += 1
    BA -= 1

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

Solution (Python):
n = int(input())
s = [list(input()) for i in range(n)]
a,b,c = 0,0,0
t = 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":
                        c += 1
                else:
                        continue
        if s[i][0] == "B":
                b += 1
        if s[i][-1] == "A":
                a += 1
        if s[i][0] == "B" and s[i][-1] == "A":
                t += 1
 
if a > b:
        d = b
else:
        d = a

if  t == b and a == t:
        d -= 1
if  t == 0 and a == 0 and b ==0:
        d += 1

print(d + c)

Solution (Python):
def solve():
    N = int(input())
    words = ["a"]*N
    for i in range(N):
        words[i] = list(input())
    A_list = []
    B_list = []
    AB_list = [] 
    AB_count = 0
    for i in range(N):
        tag_A = tag_B = tag_AB = 0
        for j in range(len(words[i])):
            if words[i][j] == "A" and j == len(words[i])-1:
                tag_A = 1
                tag_AB = 0
            elif words[i][j] == "A":
                tag_AB = 1
            elif words[i][j] == "B" and tag_AB == 1:
                tag_AB = 0
                AB_count += 1
            elif words[i][j] == "B" and j == 0:
                tag_B = 1
                tag_AB = 0
            else:
                tag_AB = 0
        if tag_A == 1 and tag_B == 1:
            AB_list.append(i)
        elif tag_A == 1:
            A_list.append(i)
        elif tag_B == 1:
            B_list.append(i)

    if len(AB_list) > 0 and len(A_list) > 0 and len(B_list) > 0:
        count = AB_count + len(AB_list) + min(len(A_list),len(B_list))
    elif len(AB_list) > 0 and len(A_list) == 0 and len(B_list) == 0:
        count = AB_count + len(AB_list) -1
    elif len(AB_list) > 0 and (len(A_list) == 0 or len(B_list) == 0):
        count = AB_count + len(AB_list)
    else:
        count = AB_count + min(len(A_list),len(B_list))

    print(count)


solve()

Solution (Python):
n = int(input())
s = [list(input()) for i in range(n)]
a,b,c = 0,0,0
t = 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":
                        c += 1
                else:
                        continue
        if s[i][0] == "B":
                b += 1
        if s[i][-1] == "A":
                a += 1
        if s[i][0] == "B" and s[i][-1] == "A":
                t += 1
 
if a > b:
        d = b
else:
        d = a

if  t == b and a == t:
        d -= 1
if  t == 0 and a == 0 and b ==0:
        d += 1

print(d + c)

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

ans = 0
initb = 0
lasta = 0
add = 0
juuhuku = 0
flag = 0

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

    if st[0] == "B":
        initb += 1

        if st[len(st)-1] == "A":
            lasta += 1
            juuhuku += 1
        else:
            flag += 1

    elif st[len(st)-1] == "A":
        lasta += 1
        flag += 1

    for j in range(len(st)):

        if st[j] == "A":

            if j == len(st) - 1:
                break
            if st[j+1] == "B":
                ans += 1

if initb <= lasta:
    add = initb
else:
    add = lasta

if juuhuku > 0:

    if flag > 0:
        ans = ans + add 
    else:
        ans = ans + add -1

else:
    ans = ans + add

print(ans)

Solution (Python):

import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
input = sys.stdin.readline
 


 
def main():
	
	N = int(input())

	S = []
	xA = 0
	Bx = 0
	BA = 0
	for _ in range(N):
		tmp = input()
		tmp = tmp[:-1]
		S.append(tmp)
		if tmp[0] == "B" and tmp[-1] == "A":
			BA += 1
			continue
		if tmp[-1] == "A":
			xA += 1
		if tmp[0] == "B":
			Bx += 1

	ans = 0
	for i, val in enumerate(S):
		tmp = val.split("AB")
		ans = ans + len(tmp) -1

	
	
	pls = 0
	if xA > 0 and Bx > 0:
		xA -= 1
		Bx -= 1

		pls = pls + 1 + BA
		BA = 0
	
	
	pls2 = 0
	if xA > 0 and Bx == 0 and BA > 0:
		xA -= 1
		pls2 = BA
		BA = 0
	
	
	pls3 = 0
	if Bx > 0 and xA == 0 and BA > 0:
		Bx -= 1
		pls3 = BA
		BA = 0
	
	
	pls4 = 0
	if Bx == 0 and xA == 0 and BA > 0:
		pls4 = BA - 1
		BA = 0
	
	
	plspls = pls + pls2 + pls3 + pls4 + min(xA, Bx)
	
	print(ans + min(plspls, N - 1))

	
if __name__ == "__main__":
	main()

Solution (Python):
n = int(input())
S = []
ans = 0
numA = 0
numB = 0
numBA = 0
for _ in range(n):
    s = input()
    ans += s.count("AB")
    if s[-1] == "A":
        if s[0] == "B":
            numBA += 1
        else:
            numA += 1
    elif s[0] == "B":
        numB += 1

if numBA == 0:
    ans += min(numA, numB)
else:
    if numA > 0:
        if numB > 0:
            ans += numBA + 1 + min(numA - 1, numB - 1)
        else:
            ans += numBA
    else:
        if numB > 0:
            ans += (numBA - 1) + 1
        else:
            ans += numBA - 1

print(ans)

Solution (Python):
N=int(input())
s=' '
num_AB=0
num_A=0
num_B=0
num_A_and_B=0
for i in range(0,N):
    s=str(input())
    if(s[0]=='B' and s[-1]=='A'):
        num_A_and_B+=1
    elif(s[0]=='B'):
        num_B+=1
    elif(s[-1]=='A'):
        num_A+=1
    for j in range(0,len(s)-1):
        if(s[j]=='A' and s[j+1]=='B'):
            num_AB+=1;

ans=num_AB
if(num_A_and_B>0):
    ans+=(num_A_and_B-1)
if(num_A_and_B>0 and num_A>0):
    num_A-=1
    ans+=1
if(num_A_and_B>0 and num_B>0):
    num_B-=1
    ans+=1
ans=ans+min(num_A,num_B)
print(ans)

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

if n == 1:
  print(cnt)
  exit()

if f >= 1:
  if a >= 1:
    cnt += 1
    a -= 1
  if b >= 1:
    cnt += 1
    b -= 1
print(cnt + max(0, f - 1) + min(a, b))

Solution (Python):
n = int(input())
s = [input() for u in range(n)]
a = sum([u.count("AB") for u in s])
b = len([1 for u in s if u.endswith("A")])
c = len([1 for u in s if u.startswith("B")])
d = len([1 for u in s if u.endswith("A") and u.startswith("B")])
if (b>0 and b==c and c==d):
  print(a+b-1)
else:
  print(a+min(b,c))

Solution (Python):
n = int(input())
x = 0
a = 0
b = 0
flag = True
for _ in range(n):
    s = input()
    if s[0] == 'B':
        b += 1
    if s[-1] == 'A':
        a += 1
    if s[0] == 'B' and s[-1] == 'A':
        pass
    elif s[0] == 'B' or s[-1] == 'A':
        flag = False
    for i in range(len(s)-1):
        if s[i:i+2] == 'AB':
            x += 1
if a == 0 or b == 0:
    print(x)
elif a == b and flag:
    print(x + a - 1)
else:
    print(x + min(a,b))

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

minimum = 0
headB = 0
lastA = 0
both = 0

strs = []
for _ in range(N):
    s = input()
    minimum += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        both += 1
    else:
        if s[0] == 'B':
            headB += 1
        if s[-1] == 'A':
            lastA += 1

combi = 0
combi += min(lastA, headB)
lastA -= combi
headB -= combi

extra = 0
if lastA > 0:
    extra = min(lastA, both)
    lastA -= extra
    both -= extra
elif headB > 0:
    extra = min(headB, both)
    headB -= extra
    both -= extra

bonus = 0
if both > 0:
    if combi > 0 or extra > 0:
        bonus = both
    else:
        bonus = both-1

result = minimum + combi + extra + bonus

print(result)

Solution (Python):
N = int(input())
ans = 0
d = {'A':0,'B':0,'BA':0}
for i in range(N):
    s = input()
    ans += s.count('AB')
    if s[0]!='B' and s[-1]!='A':
        continue
    else:
        if s[0]+s[-1]=='BA':
            d['BA']+=1
        else:
            if s[0]=='B':
                d['B']+=1
            else:
                d['A']+=1
        
ans += min(d['A'],d['B'])
if d['A']==0 and d['B']==0:
    ans += max(0,d['BA']-1)
else:
    ans += d['BA']
print(ans)

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

    inner = 0
    for s in S:
        inner += s.count("AB")
    
    
    

    A_ended = 0
    B_begin = 0
    both = 0
    for s in S:
        if s[0] == "B" and s[-1] == "A":
            both += 1   

        elif s[0] == "B": B_begin += 1
        elif s[-1] == "A": A_ended += 1

    mmA = 0
    if both > 0:
        if A_ended > 0:
            mmA += 1
            A_ended-=1
        if B_begin > 0:
            mmA += 1
            B_begin -= 1

    mmA += min(A_ended, B_begin)    
    if both > 0:
        mmA += both-1

    
    
    
    
    
    
    print(inner + mmA )
    

if __name__ == "__main__":
    solve()

Solution (Python):

from collections import defaultdict
from collections import deque

N = int(input())
ss = list()
for i in range(N):
    ss.append(input())

types = list()
indices_dict = defaultdict(deque)
for i, s in enumerate(ss):
    if s[-1] == 'A':
        if s[0] != 'B':
            type_ = 0
        else:
            type_ = 1

    elif s[0] == 'B':
        type_ = 2
    else:
        type_ = 3
    types.append(type_)
    indices_dict[type_].append(i)


indices = list()
type_prev = 3
while True:
    
    
    if type_prev in {2, 3}:
        if len(indices_dict[0]) != 0:
            idx = indices_dict[0].pop()
            indices.append(idx)
            type_prev = 0
        elif len(indices_dict[1]) != 0:
            idx = indices_dict[1].pop()
            indices.append(idx)
            type_prev = 1
        elif len(indices_dict[3]) != 0:
            idx = indices_dict[3].pop()
            indices.append(idx)
            type_prev = 3
        elif len(indices_dict[2]) != 0:
            idx = indices_dict[2].pop()
            indices.append(idx)
            type_prev = 2
        else:
            break

    
    else:
        if len(indices_dict[1]) != 0:
            idx = indices_dict[1].pop()
            indices.append(idx)
            type_prev = 1
        elif len(indices_dict[2]) != 0:
            idx = indices_dict[2].pop()
            indices.append(idx)
            type_prev = 2
        elif len(indices_dict[3]) != 0:
            idx = indices_dict[3].pop()
            indices.append(idx)
            type_prev = 3
        elif len(indices_dict[0]) != 0:
            idx = indices_dict[0].pop()
            indices.append(idx)
            type_prev = 0
        else:
            break

st = ''
for idx in indices:
    st += ss[idx]

ans = 0
for i in range(len(st) - 1):
    if st[i] == 'A':
        if st[i + 1] == 'B':
            ans += 1
print(ans)

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

s = []
Binfront = 0
Ainend = 0
bothAB = 0
ABs = 0
for i in range(N):
    inputstring = input()
    s.append(inputstring)
    ABs += inputstring.count("AB")
    
    if inputstring[0] == "B" and inputstring[len(inputstring)-1] == "A":
        bothAB += 1
    elif inputstring[0] == "B":
        Binfront += 1
    elif inputstring[len(inputstring)-1] == "A":
        Ainend += 1


if bothAB > 0:
    ABs += bothAB - 1
    if Ainend > 0:
        ABs += 1
        Ainend -= 1
    if Binfront > 0:
        ABs += 1
        Binfront -= 1
ABs += min(Ainend,Binfront)

print(ABs)

Solution (Python):
N = int(input())
S = []
for i in range(N):
    S.append(input())
cnt = 0
cntA = 0
cntB = 0
cntAB = 0
for s in S:
    cnt += s.count('AB')
for s in S:
    if s[0] == 'B':
        cntB += 1
    if s[-1] == 'A':
        cntA += 1
    if s[0]=='B' and s[-1] =='A':
        cntAB += 1
if cntA == cntB == cntAB != 0:
    print(cnt + cntAB - 1)
else:
    print(cnt + min(cntA, cntB))

Solution (Python):

import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, S):
    ans = 0
    pre_b = set()
    post_a = set()
    for i, s in enumerate(S):
        if s[0] == 'B':
            pre_b.add(i)
        if s[-1] == 'A':
            post_a.add(i)
        ans += s.count('AB')
    
    both = pre_b & post_a
    if both:
        ans += len(pre_b & post_a) - 1
    pre_b -= both
    post_a -= both
    
    pbl = len(pre_b)
    pal = len(post_a)
    if both:
        if pbl == 0 and pal == 0:
            pass
        elif pbl == 0:
            
            ans += min(1, pal)
        elif pal == 0:
            ans += min(1, pbl)
        else:
            ans += min(pbl+1, pal+1)
    else:
        ans += min(pbl, pal)
    return ans


def slv2(N, S):
    ans = 0
    for i in permutations(range(N), N):
        ans = max(ans, ''.join([S[j] for j in i]).count('AB'))
    return ans


def main():
    N = read_int()
    S = [read_str() for _ in range(N)]
    print(slv(N, S))
    

    
    
    
    
    
    


if __name__ == '__main__':
    main()

Solution (Python):
n = int(input())
ans = 0
a = 0
b = 0
both = 0

for i in range(n):
    s = input()
    ans += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        both += 1
    elif s[0] == 'B':
        b += 1
    elif s[-1] == 'A':
        a += 1
if a <= 0 or b <= 0:
    if a <= 0 and b <= 0:
        if both-1 > 0:
            ans += both-1
    else:
        ans += both
else:
    b -= 1
    a -= 1
    ans += both+1 + min(a,b)
print(ans)

Solution (Python):
N = int(input())
S = []
count = 0
countA = 0
countB = 0
countAB = 0
for i in range(N):
	S_in = str(input())
	for j in range(len(S_in)-1):
		if S_in[j:j+2] == 'AB':
			count += 1
	if (S_in[0] == 'B') & (S_in[-1] == 'A'):
		countAB	+= 1
	elif S_in[0] == 'B':
		countB += 1
	elif S_in[-1] == 'A':
		countA += 1
	S.append(S_in)
if (countA == 0) & (countB == 0) & (countAB > 0):
	print(max(0, count + countAB - 1))
else:
	print(count + countAB + min(countA, countB))

Solution (Python):

n = int(input())
a = []
for i in range(n):
  a.append(input())

cnt = 0

ba=0
bx=0
xa=0

for s in a:
  for i in range(len(s)):
    if i < 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':
    bx += 1
  elif s[-1:]=='A':
    xa += 1

if ba > 1:
  cnt += ba-1
  ba = 1
babx = min(ba,bx)

xaba = min(xa,ba)

xaax = min(bx - babx,xa-xaba)


print(cnt+babx+xaba+xaax)

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

cnt = 0
cnt1 = 0
cnt2 = 0
cnt3 = 0
for x in s:
    cnt += x.count("AB")
    if x[0] == "B":
        cnt1 += 1
    if x[-1] == "A":
        cnt2 += 1
    if x[0] == "B" and x[-1] == "A":
        cnt3 += 1

cnt1 -= cnt3
cnt2 -= cnt3

if cnt1+cnt2 > 0 or cnt3 == 0:
    print(cnt + cnt3 + min(cnt1, cnt2))
else:
    print(cnt + cnt3 + min(cnt1, cnt2) - 1)

Solution (Python):
n=int(input())
ss=[]
for _ in range(n):
    s=input()
    if 'A' in s or 'B' in s:
        ss.append(s)
c = sum(s.count('AB') for s in ss)
a = min(sum(s[0] == 'B' for s in ss), sum(s[-1] == 'A' for s in ss))
if a:
    c += a
    if sum((s[0] == 'B' and s[-1] != 'A') or (s[0] != 'B' and s[-1] == 'A') for s in ss) == 0:
        c -= 1
print(c)

Solution (Python):



N = int(input())

num_ab = 0
last_a = 0
top_b = 0
double_ab = 0



s = []
for i in range(N):
    s.append(str(input()))
for i in range(N):
    num_ab += s[i].count("AB")
    if s[i][0] == "B":
        if s[i][-1] == "A":
            double_ab += 1
        else:
            top_b += 1
    if s[i][-1] == "A":
        if s[i][0] != "B":
            last_a += 1

ans = 0
ans += num_ab
if double_ab > 0:
    ans += double_ab - 1
    if last_a > 0:
        ans += 1
        last_a -= 1
    if top_b > 0:
        ans += 1
        top_b -= 1
    ans += min(last_a,top_b)
else:
    ans += min(last_a,top_b)
print(ans)

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

count = 0
Acount = 0
AScount = 0
Bcount = 0
BScount = 0
BAcount = 0

for i in range(N):
    s = input()
    if 1 < len(s):
        if 'AB' in s:
            count += s.count('AB')
        if s[0] == 'B' and s[-1] == 'A':
            BAcount += 1
        elif s[0] == 'B':
            Bcount += 1
        elif s[-1] == 'A':
            Acount += 1
    else:
        if s == 'B':
            BScount += 1
        if s == 'A':
            AScount += 1

BAcount += min(BScount, AScount)

if BScount <= AScount:
    Acount += AScount - BScount
else:
    Bcount += BScount - AScount

if 0 < BAcount:
    count += BAcount - 1
    BAcount = 1

if 0 < Acount and 0 < BAcount:
    count += 1
    Acount -= 1

if 0 < Bcount and 0 < BAcount:
    count += 1
    Bcount -= 1

count += min(Bcount, Acount)
print(count)

Solution (Python):
from sys import stdin
import math
import fractions
from collections import deque

INF = 10 ** 10

N = int(stdin.readline().rstrip())
s = [stdin.readline().rstrip() for _ in range(N)]

endA_num = 0
startB_num = 0
endA_startB_num = 0

cnt = 0
for si in s:
    if si[-1] == "A":
        endA_num += 1
        if si[0] == "B":
            endA_startB_num += 1
    if si[0] == "B":
        startB_num += 1

    for i in range(len(si)-1):
        if si[i] == "A" and si[i+1] == "B":
            cnt+=1

alpha = 0
if endA_num > 0 and startB_num > 0:
    if endA_num == startB_num and endA_num == endA_startB_num:
        endA_num -= 1
    alpha = min(endA_num, startB_num)

print(cnt+alpha)

Solution (Python):

N = int(input())

count = 0
count_a = 0
count_b = 0
count_all = 0
for i in range(N):
    s = input()
    for j in range(1,len(s)):
        if s[j] == 'B' and s[j-1] == 'A':
            count += 1
    if s[0] == 'B' and s[-1] == 'A':
        count_all += 1
        continue
    if s[0] == 'B':
        count_b += 1
    if s[-1] == 'A':
        count_a += 1

mx = max(count_a, count_b)
mn = min(count_a, count_b)
ans = count + mn
if count_all != 0:
    if count_a != 0 and count_b != 0:
        ans = count + (count_all-1+2) + (mn-1)
    if count_a == 0 and count_b == 0:
        ans = count + count_all - 1
    if count_a == 0 and count_b != 0:
        ans = count + count_all - 1 + 1
    if count_a != 0 and count_b == 0:
        ans = count + count_all -1 + 1

print(ans)

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


cnt_ba = 0
cnt_a = 0
cnt_b = 0
ans = 0
for i in range(n):
      s = input()
      ans += s.count("AB")
      if s[0] == "B" and s[-1] == "A":
            cnt_ba += 1
      elif s[0] == "B":
            cnt_b += 1
      elif s[-1] == "A":
            cnt_a += 1
if n != 1:
      if cnt_ba != 0:
            tmp = cnt_ba-1
            if  cnt_a >= 1:
                  tmp += 1
                  cnt_a -= 1
            if  cnt_b >= 1:
                  tmp += 1
                  cnt_b -= 1
      else: tmp = 0
      print(ans + tmp + min(cnt_a, cnt_b))
else:
      print(ans)

Solution (Python):
N = int(input())
s = []
temp_sum = 0
A_or_B_count = [0,0]
AB_count = 0
for i in range(N):
	aaa = input()
	temp_sum += aaa.count("AB")
	if aaa[0] == "B" and aaa[-1] == "A":
		AB_count += 1
	elif aaa[-1] == "A":
		A_or_B_count[0] += 1
	elif aaa[0] == "B":
		A_or_B_count[1] += 1
A_or_B_count.sort()
if A_or_B_count[0] + AB_count > A_or_B_count[1]:
	if A_or_B_count[1] == 0:
		print(temp_sum + min(N-1,AB_count - 1))
	else:
		AB_count -= (A_or_B_count[1] - A_or_B_count[0])
		print(temp_sum + min(N-1,AB_count + A_or_B_count[1]))
else:
	print(temp_sum + min(N - 1,A_or_B_count[0] + AB_count))

Solution (Python):
N = int(input())
ans = 0
numb = 0
numa = 0
numba = 0
for _ in range(N):
    s = input()
    ans += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        numba += 1
    elif s[0] == "B":
        numb += 1
    elif s[-1] == "A":
        numa += 1

if numa == 0:
    if numb == 0:
        ans += max(0, numba - 1)
    else:
        ans += numba
else:
    if numba == 0:
        ans += min(numa, numb)
    elif numb == 0:
        ans += numba
    else:
        numa -= 1
        ans += numba + 1
        numb -= 1
        ans += min(numa, numb)
print(ans)

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

Solution (Python):
def countAB(S):
  ct=0
  flg = True
  pos=0
  while flg:
    idx = S.find('AB',pos)
    if idx!=-1:
      ct+=1
    else:
      flg = False
    pos = idx + 2
  return ct
 
N = int(input())
 
num_AB = 0
num_A = 0
num_B = 0
num_BA = 0
for n in range(N):
  S = input()
  num_AB += countAB(S)
  if S[len(S)-1]=='A':
    num_A += 1
  if S[0]=='B':
    num_B += 1
  if S[len(S)-1]=='A' and S[0]=='B': 
    num_BA += 1
    
num_AB_cmb = min(num_A,num_B)
if num_A == num_BA and num_B == num_BA and num_BA!=0:
  num_AB_cmb = num_BA-1
 
print("{0}".format(num_AB + num_AB_cmb))

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

ans = 0
A = B = BA = 0
for s in S:
    for i in range(len(s) - 1):
        if s[i] + s[i + 1] == 'AB':
            ans += 1

    if s[-1] == 'A' and s[0] == 'B':
        BA += 1
    elif s[-1] == 'A':
        A += 1
    elif s[0] == 'B':
        B += 1


if (A > 0) & (B > 0) & (BA > 0):
    ans += BA + 1
    A, B = A - 1, B - 1
    ans += min(A, B)

elif (A > 0) & (B > 0):
    ans += min(A, B)

elif A > 0:
    ans += BA

elif B > 0:
    ans += BA

elif BA > 0:
    ans += (BA - 1)

print(ans)

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

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

if a>b :
    print(ab+b)
elif a!=0 and a==b and bxxa==a:
    print(ab+a-1)
else: 
    print(ab+a)

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

a = 0
both = 0
b = 0
ans = 0
for i, s in enumerate(s_list):
    ans += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        both += 1

    elif s[-1] == "A":
        a += 1

    elif s[0] == "B":
        b += 1

if a != 0:
    a -= 1
    ans += both
    if b != 0:
        b -= 1
        ans += 1
    ans += min(a, b)
else:
    if b != 0:
        b -= 1
        ans += both
    else:
        if both >= 2:
            ans += both - 1
print(ans)

Solution (Python):

import sys

import heapq
import re
import bisect
import random
import math
import itertools
from collections import defaultdict, deque
from copy import deepcopy
from decimal import *

n = int(input())
AA = []
BA = []
BZ = []

AZ = []

count = 0
l = 0
AAc = 0
BAc = 0
BZc = 0
for i in range(n):
    t = input()
    count += t.count('AB')
    ss = list(t)
    if ss[0] == 'B' and ss[-1] == 'A':
        BA.append(1)
        BAc += 1
        l += 1
    elif ss[0] != 'B' and ss[-1] == 'A':
        AA.append(1)
        AAc += 1
        l += 1
    elif ss[0] == 'B' and ss[-1] != 'A':
        BZ.append(1)
        BZc += 1
        l += 1
if AAc != 0 and BAc != 0:
    count += BAc
    AAc -= 1
    if BZc != 0:
        BZc -= 1
        count += 1
    if AAc != 0 and BZc !=0:
        count += min(AAc,BZc)
elif AAc == 0 and BAc != 0:
    if BAc >= 2:
        count += BAc - 1
    if BZc > 0:
        count += 1
elif AAc != 0 and BAc ==0:
    count += min(AAc, BZc)
print(count)

Solution (Python):
n = int(input())
c = 0
xa = 0
bx = 0
ba = 0
for _ in range(n):
  si = str(input())
  l = len(si)
  s1 = si[0]
  s2 = si[-1]
  if s1=="B":
    if s2=="A":
      ba += 1
    else:
      bx += 1
  elif s2 == "A":
    xa += 1
  for i in range(l-1):
    if si[i]=="A" and si[i+1]=="B":
      c += 1
if ba == 0:
  print(c+min(bx,xa))
  exit()
if bx == 0:
  if  xa == 0:
    print(ba-1+c)
    exit()
  else:
    print(ba+c)
    exit()
if xa == 0:
  print(ba+c)
  exit()
print(min(bx,xa)+ba+c)

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

start = 0
end = 0
same = 0
c = 0
for x in s:
    c = c + len(x.split('AB')) - 1
    if x.startswith('B'):
        start += 1
        if x.endswith('A'):
            same += 1
    if x.endswith('A'):
        end += 1

if start == end:
    c += start
    if same > 0 and same == start:
        c  -= 1
elif start > end:
    c += end
else:
    c += start
print(c)

Solution (Python):
N = int(input())
c = 0
tail_A = 0
head_B = 0
B_A = 0
def count(S):
    if len(S) == 1:
        return 0
    c = 0
    for i in range(len(S)-1):
        if S[i] == 'A' and S[i+1] == 'B':
            c += 1
    return c

for _ in range(N):
    s = input()
    c += count(s)
    if s[-1] == 'A':
        if s[0] == 'B':
            B_A += 1
        else:
            tail_A += 1
    else:
        if s[0] == 'B':
            head_B += 1

if tail_A > 0 and head_B > 0:
    c = c + B_A + 1
    tail_A -= 1
    head_B -= 1
elif tail_A == 0 and head_B > 0:
    c = c + B_A
    head_B -= 1
elif tail_A > 0 and head_B == 0:
    c = c + B_A
    tail_A -= 1
else:
    if B_A >= 2:
        c = c + B_A - 1

c += min(tail_A, head_B)
print(c)

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

cnt = 0
enda = 0
startb = 0
ba = 0
for s in strs:
    cnt += s.count("AB")
    enda += 1 if (s[-1] == "A") else 0
    startb += 1 if (s[0] == "B") else 0
    ba += 1 if (s[0] == "B" and s[-1] == "A") else 0

cnt -= 1 if (ba != 0 and enda == ba and startb == ba) else 0

print(cnt + min(enda, startb))

Solution (Python):
n,*s=open(0)
a=b=c=d=0
for t in s:
    if t[-2]=='A'and t[0]=='B':
        d+=1
    elif t[-2]=='A':
        a+=1
    elif t[0]=='B':
        b+=1
    c+=t.count('AB')
if all(i==0for i in(a,b)):
    print(c+max(0,d-1))
    exit()
elif a==b:
    print(a+c+d)
    exit()
ans=min(a,b)+c
dif=abs(a-b)
ans+=min(dif,d)
d-=min(dif,d)
print(ans+d)

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

BA = 0
start_B = 0
end_A = 0

ans = 0
for _ in range(N):
    s = list(input())
    if s[0] == 'B' and s[-1] == 'A':
        BA += 1
    elif s[0] == 'B':
        start_B += 1
    elif s[-1] == 'A':
        end_A += 1
    for i in range(len(s)-1):
        if s[i] == 'A' and s[i+1] == 'B':
            ans += 1
ans += min(start_B, end_A)
if BA > 0:
    ans += BA - 1
if (start_B > 0 or end_A > 0) and BA > 0:
    ans += 1
print(ans)

Solution (Python):

N = int(input())
countA = 0
countB = 0
countC = 0
kcount = 0

for i in range(N):
    K = input()
    kcount += K.count("AB")
    K = list(K)
    if K[0] == "B" and K[-1] == "A":
        countC += 1 
    if K[-1] == "A":
        countA += 1
    if K[0] == "B":
        countB += 1
if countC>=1 and (countB-countC)==0 and (countA-countC)==0:
    print(kcount+countC-1)
elif countC >=1 and (countB-countC)==0 and (countA-countC)>=1:
    print(kcount+countC)
elif countC >=1 and (countB-countC)>=1 and (countA-countC)==0:
    print(kcount+countC)
elif countB > countA:
    print(kcount+countA)
else:
    print(kcount+countB)

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

c = 0
ca = 0
cb = 0
cab = 0

for s in sl:
  c += s.count('AB')
  if s[-1] == 'A':
    ca += 1
  if s[0] == 'B':
    cb += 1
  if s[-1] == 'A' and s[0] == 'B':
    cab += 1

t = min(ca, cb)
if ca == cb and cb == cab and ca > 0:
  t -= 1
print(c + t)

Solution (Python):
def solve():
    N = int(raw_input())
    S = []
    for i in range(N):
        S.append(raw_input())
    has_AB = 0
    end_byA = 0
    start_byB = 0
    B_A = 0
    for i in range(N):
        if S[i][0] == 'B':
            if S[i][-1] == 'A':
                B_A += 1
            else:
                start_byB += 1
        if S[i][-1] == 'A':
            if S[i][0] != 'B':
                end_byA += 1
        for j in range(len(S[i]) - 1):
            if S[i][j:(j+2)] == 'AB':
                has_AB += 1
    if end_byA == 0 and start_byB == 0:
        ret = has_AB + max(B_A - 1, 0)
    else:
        ret = has_AB + min(end_byA + B_A, start_byB + B_A)
    print str(ret)

if __name__ == '__main__':
    solve()

Solution (Python):
N = int(input())
s = []
ab_num = 0
b_start = 0
a_end = 0
ba_word = 0
for i in range(N):
    tmp = input()
    s.append(tmp)
    rep = tmp.replace("AB", "")
    ab_num += (len(tmp) - len(rep)) // 2
    if tmp[0] == "B":
        b_start += 1
    if tmp[-1] == "A":
        a_end += 1
    if tmp[0] == "B" and tmp[-1] == "A":
        ba_word += 1
if b_start == a_end == ba_word != 0:
    print(max(ab_num + min(a_end, b_start) - 1, 0))
else:
    print(ab_num + min(a_end, b_start))

Solution (Python):
N = int(input())
c = 0
A = 0
B = 0
BA = 0
for i in range(N):
  tmp = input()
  if (tmp[0] == 'B') & (tmp[-1] == 'A'):
    BA += 1
  elif (tmp[0] == 'B'):
    B += 1
  elif (tmp[-1] == 'A'):
    A += 1 
  c += tmp.count('AB')
if BA >= 1:
  c += BA-1
  if B >= 1:
    B -=1
    c += 1
  if A >= 1:
    A -= 1
    c += 1
c += min(A,B)
print(c)

Solution (Python):
import re

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

counter = 0
B_begin=0
A_end =0
AB_in =0
B_begin_and_A_end = 0


for i in range(N):
    m = len(re.findall('AB',s[i]))
    AB_in += m

    chech_b = False
    chech_a = False

    if s[i][0]=='B':
        B_begin +=1
        chech_b = True

    if s[i][-1]=='A':
        A_end+=1
        chech_a = True

    if chech_a and chech_b:
        B_begin_and_A_end+=1

ans = 0 
mini = min(B_begin, A_end)

if mini ==0:
    ans = AB_in

elif B_begin == A_end == B_begin_and_A_end:
    if mini!=0:
        ans = AB_in + mini -1

else:
    ans = AB_in + mini

print(ans)

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

base = sum(x.count('AB') for x in s)

same_pattern = a_n = b_n = 0
for x in s:
    b = x[0]
    a = x[len(x)-1]
    if b == 'B':
        b_n += 1
    if a == 'A':
        a_n += 1
    if a == 'A' and b == 'B':
        same_pattern += 1

if same_pattern > 0 and same_pattern == max(a_n, b_n):
    print(base + max(a_n, b_n) - 1)
else:
    print(base + min(a_n, b_n))