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())
count=0
bx=0
xa=0
ba=0
for i in range(n):
    s=input()
    for j in range(0,len(s)-1):
        if s[j:j+2]=='AB':
            count=count+1
    if s[0]=='B' and s[len(s)-1]=='A':
        ba=ba+1
    if s[0]=='B' and not s[len(s)-1]=='A':
        bx=bx+1
    if not s[0]=='B' and s[len(s)-1]=='A':
        xa=xa+1
if bx==0 and xa==0:
    if ba>=2:
        count=count+ba-1
else:
    count=count+ba+min(xa,bx)
print(count)

Solution (Python):

import re

n=int(input())
string_list=[input() for i in range(n)]

count = 0

match_both_count = 0
match_start_count = 0
match_end_count = 0

for i in range(len(string_list)):
  match = re.findall(r"AB", string_list[i])
  if (match):
    count += len(match)

  match_both = re.match(r"^B.*A$", string_list[i])
  if match_both:
    match_both_count += 1
  else:
    match_start = re.match(r"^B.*$", string_list[i])
    if match_start:
      match_start_count += 1
      continue

    match_end = re.match(r"^.*A$", string_list[i])
    if match_end:
      match_end_count += 1
      continue

combination = 0
if match_both_count > 0:
  combination += match_both_count - 1

  if match_start_count > 0:
    combination += 1
    match_start_count -= 1

  if match_end_count > 0:
    combination += 1
    match_end_count -= 1

print(combination + min(match_start_count, match_end_count) + count)

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

a = 0
b = 0
ab = 0
ba = 0
for i in s:
  if i[0] == "B":
    b += 1
  if i[-1] == "A":
    a += 1
  if i[0] == "B" and i[-1] == "A":
    ba += 1
  ab += i.count("AB")
  
if ba != 0 and ba == b:
  aa = a - 1
else:
  aa = a
if ba != 0 and ba == a:
  bb = b - 1
else:
  bb = b
  
print(min(aa, bb) + ab)

Solution (Python):


import math
import re

def main(params):
    total = 0
    a = []
    b = []
    for i in range(len(params)):
        s = params[i]
        total += s.count("AB")
        if s[0] == "B":
            b.append(i)
        if s[-1:] == "A":
            a.append(i)
    if min(len(a),len(b)) > 0 and len(a) == len(b):
        total += min(len(a), len(b))
        chk = True
        for i in a:
            if not i in b:
                chk = False
        if chk == True:
            total -= 1
    else:
        total += min(len(a),len(b))
    print total

if __name__ == "__main__":
    n = int(raw_input())
    
    params = []
    for i in range(n):
        param = raw_input()
        params.append(param)
    main(params)

Solution (Python):
N=int(input())
S=[input() for _ in [0]*N]
AB=0
X_A=0
B_X=0
B_A=0
for s in S:
    AB+=s.count("AB")
    if s[0]!="B" and s[-1]=="A":X_A+=1
    if s[0]=="B" and s[-1]!="A":B_X+=1
    if s[0]=="B" and s[-1]=="A":B_A+=1
r=AB
if B_A>0:
    r+=B_A-1
    if X_A>0:r+=1;X_A-=1
    if B_X>0:r+=1;B_X-=1
r+=min(X_A,B_X)
print(r)

Solution (Python):
n = int(input())
count_ab = 0
tail_a = 0
head_b = 0
hb_ta = 0
ans = 0
for i in range(n):
    s = str(input())
    if s[0] == "B" and s[-1] == "A":
        hb_ta += 1
    elif s[0] == "B":
        head_b += 1
    elif s[-1] == "A":
        tail_a += 1
    for j in range(len(s)-1):
        if s[j:j+2] == "AB":
            count_ab += 1

if tail_a > 0 and head_b > 0:
    ans = 1 + hb_ta
    ans += min(tail_a-1, head_b-1)
elif tail_a > 0 or head_b > 0:
    
    ans = hb_ta
else:
    
    if hb_ta > 0:
        ans = hb_ta - 1
    else:
        ans = 0
ans += count_ab
print(ans)

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

if d["B_A"] == 0 and d["A"] == 0:
    pass
elif d["B_A"] == 0:
    ans += min(d["A"], d["B"])
elif d["A"] == 0:
    if d["B"] == 0:
        ans += d["B_A"]-1
    else:
        ans += d["B_A"]
else:
    if d["B"] == 0:
        ans += d["B_A"]
    else:
        ans += d["B_A"]+1 + min(d["A"]-1, d["B"]-1)
print(ans)

Solution (Python):
from sys import stdin
N = int(input())

middle = 0
countB = 0
countA = 0
countBA = 0
sumcount = 0

for i in range(N):
    s = input()
    middle += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        countBA +=1
    elif s[0] == "B":
        countB +=1
    elif s[-1] == "A":
        countA +=1
if countBA > 0:
    sumcount += countBA -1
    if countA > 0:
        sumcount +=1
        countA -= 1
    if countB > 0:
        sumcount +=1
        countB -= 1

t = min(countA, countB)

print(sumcount+middle+t)

Solution (Python):


def readInts():
  return [int(s) for s in input().split(" ")]

def main():
  N = readInts()[0]

  ans = 0

  nAts = 0
  nBlsAts = 0
  nBls = 0

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

    if s[0] == "B" and s[-1] == "A":
      nBlsAts += 1
    elif s[0] == "B":
      nBls += 1
    elif s[-1] == "A":
      nAts += 1

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

  if nBlsAts > 0:
    ans += nBlsAts - 1

  if nBlsAts > 0:
    if nAts > 0:
      nAts -= 1
      ans += 1
    if nBls > 0:
      nBls -= 1
      ans += 1

  ans += min(nAts, nBls)

  print(ans)

if __name__ == "__main__":
  main()

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

Solution (Python):
N=int(input())
btoa=0
enda=0
startb=0
ab=0
for i in range(N):
	buf=input()
	if buf[0]=="B" and buf[-1]=="A":
		btoa+=1
	elif buf[-1]=="A":
		enda+=1
	elif buf[0]=="B":
		startb+=1
	ab+=buf.count("AB")
if btoa>=1:
	res=ab+btoa-1
	if enda!=0 or startb!=0:
		enda+=1
		startb+=1
		print(res+min(enda,startb))
	else:
		print(res)
else:
	print(ab+min(enda,startb))

Solution (Python):
N =int(input())
co = {0:0,1:0,2:0,3:0}
ans = 0
foo =0
for _ in range(N):
    i = input()
    foo = 0
    if i[0] =="B":
        foo += 1
    if i[-1] =="A":
        foo += 2
    co[foo] += 1
    ans += i.count("AB")
ans +=  min(co[1],co[2])
ans += co[3]
if co[1]==0 and co[2] == 0 and co[3]!= 0:
    ans -= 1
print(ans)

Solution (Python):
N=int(input())
end_A_only=0
start_B_only=0
both=0
count=0
for i in range(N):
    s=input()
    count+=s.count("AB")
    if s[-1]=="A" and s[0] =="B":
        both+=1
    elif s[-1]=="A":
        end_A_only+=1
    elif s[0]=="B":
        start_B_only+=1
    else:
        pass

if both==0:
    count+=min(end_A_only,start_B_only)

else:
    if end_A_only==0 and start_B_only==0:
        count+=both-1
    elif end_A_only==0 or start_B_only==0:
        count+=both
    else:
        count+=both+1
        count+=min(end_A_only-1,start_B_only-1)


print(count)

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

A = 0
B = 0
BA = 0
ans = 0
for i in range(N):
    if S[i][0] == 'B' and S[i][-1] == 'A':
        BA += 1
    elif S[i][0] == 'B':
        B += 1
    elif S[i][-1] == 'A':
        A += 1
    for j in range(len(S[i])-1):
        if S[i][j] == 'A' and S[i][j+1] == 'B':
            ans += 1
if BA > 0:
    ans += BA - 1
    if B != 0:
        A += 1
    if A != 0:
        B += 1
ans += min(A, B)
print(ans)

Solution (Python):

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


def n_ab(s):
    n = len(s)
    output = 0
    for i in range(n - 1):
        if s[i] + s[i+1] == "AB":
            output += 1

    return output


output = 0
for i in range(N):
    output += n_ab(s[i])

n_b = 0
n_a = 0
n_b_a = 0
for i in range(N):
    if s[i][0] == "B":
        if s[i][-1] == "A":
            n_b_a += 1
        else:
            n_b += 1
    elif s[i][-1] == "A":
        n_a += 1

if n_b_a == 0:
    print(output + min([n_b, n_a]))
else:
    output += n_b_a - 1

    if n_a == 0:
        if n_b == 0:
            print(output)
        else:
            print(output+1)
    else:
        if n_b == 0:
            print(output+1)
        else:
            print(output + 2 + min([n_b - 1, n_a - 1]))

Solution (Python):


from sys import stdout
from bisect import bisect_left as binl
from copy import copy, deepcopy


mod = 1


def intin():
    input_tuple = input().split()
    if len(input_tuple) <= 1:
        return int(input_tuple[0])
    return tuple(map(int, input_tuple))


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


def intinl(count):
    return [intin() for _ in range(count)]


def modadd(x, y):
    global mod
    return (x + y) % mod


def modmlt(x, y):
    global mod
    return (x * y) % mod


def lcm(x, y):
    while y != 0:
        z = x % y
        x = y
        y = z
    return x


def combination(x, y):
    assert(x >= y)

    if y > x // 2:
        y = x - y

    ret = 1

    for i in range(0, y):
        j = x - i
        i = i + 1

        ret = ret * j
        ret = ret // i

    return ret


def get_divisors(x):
    retlist = []
    for i in range(1, int(x**0.5) + 3):
        if x % i == 0:
            retlist.append(i)
            retlist.append(x // i)
    return retlist


def get_factors(x):
    retlist = []
    for i in range(2, int(x**0.5) + 3):
        while x % i == 0:
            retlist.append(i)
            x = x // i
    retlist.append(x)
    return retlist


def make_linklist(xylist):
    linklist = {}
    for a, b in xylist:
        linklist.setdefault(a, [])
        linklist.setdefault(b, [])
        linklist[a].append(b)
        linklist[b].append(a)
    return linklist


def calc_longest_distance(linklist, v=1):
    distance_list = {}
    distance_count = 0
    distance = 0
    vlist_previous = []
    vlist = [v]
    nodecount = len(linklist)

    while distance_count < nodecount:
        vlist_next = []
        for v in vlist:
            distance_list[v] = distance
            distance_count += 1
            vlist_next.extend(linklist[v])
        distance += 1
        vlist_to_del = vlist_previous
        vlist_previous = vlist
        vlist = list(set(vlist_next) - set(vlist_to_del))

    max_distance = -1
    max_v = None
    for v, distance in distance_list.items():
        if distance > max_distance:
            max_distance = distance
            max_v = v

    return (max_distance, max_v)


def calc_tree_diameter(linklist, v=1):
    _, u = calc_longest_distance(linklist, v)
    distance, _ = calc_longest_distance(linklist, u)
    return distance





def main():
    n = intin()
    slist = [input() for _ in range(n)]

    count = 0
    head_b_list = []
    tail_a_list = []

    for i, s in enumerate(slist):
        bwait = False
        for c in s:
            if c == 'A':
                bwait = True
            else:
                if c == 'B' and bwait:
                    count += 1
                bwait = False

        if s[0] == 'B':
            head_b_list.append(i)
        if s[-1] == 'A':
            tail_a_list.append(i)

    head_b_set = set(head_b_list)
    tail_a_set = set(tail_a_list)

    ba_set = tail_a_set & head_b_set
    only_a = tail_a_set - head_b_set
    only_b = head_b_set - tail_a_set

    if not only_a and not only_b:
        count += max(len(ba_set) - 1, 0)
    elif not only_a:
        count += len(ba_set)
    elif not only_b:
        count += len(ba_set)
    else:
        count += len(ba_set) + 1
        count += min(len(only_a) - 1, len(only_b) - 1)

    print(count)


if __name__ == '__main__':
    main()

Solution (Python):
n=int(input())
ans=0
a=0
b=0
num=0
for i in range(n):
    cnt=0
    s=input()
    ans+=s.count("AB")
    if s[0]=="B":
        b+=1
        cnt+=1
    if s[-1]=="A":
        a+=1
        cnt+=1
    if cnt==2:
        num+=1

print(ans+min(a,b) if num!=max(a,b) else ans+min(a,b)-1 if num!=0 else ans+min(a,b))

Solution (Python):
words = lambda t : list(map(t, input().split()))
n = int(input())

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

Solution (Python):
N = int(input())
num = 0
a = 0
b = 0
ba = 0

for _ in range(N):
    x = (input())
    num = num + x.count('AB')
    if x[0] == 'B':
        b = b + 1
        if x[-1] == 'A':
            ba = ba +1
    if x[-1] == 'A':
        a = a + 1

if ba == b and a == b and a != 0:
    print(num+b-1)
elif ba == b and a == b and a == 0:
    print(num)
else:
    print(num+min(a,b))

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

cnt1=0
B_Start=0
A_End=0
ALL=0

for i in range(N):
    cnt1 += S[i].count("AB")
    if S[i][0] == "B":
        B_Start += 1
    if S[i][-1] == "A":
        A_End += 1
    if S[i][0] == "B" or S[i][-1] == "A":
        ALL += 1

hosei=0
        
if B_Start == A_End == ALL and ALL != 0:
  hosei=1
        
print(cnt1 + min(B_Start,A_End) - hosei)

Solution (Python):
N = int(input())
s_list = []
last_a_count = 0
first_b_count = 0
both_ab_count = 0
contain_ab_count = 0
for s in range(N):
    s_list.append(input().strip())
    if(s_list[-1][-1] == "A" and s_list[-1][0] != "B"):
        last_a_count += 1
    if(s_list[-1][-1] != "A" and s_list[-1][0] == "B"):
        first_b_count += 1
    if(s_list[-1][-1] == "A" and s_list[-1][0] == "B"):
        both_ab_count += 1
    contain_ab_count += s_list[-1].count("AB")
    
ans = contain_ab_count
if(both_ab_count > 0):
    ans += both_ab_count - 1
    ans += first_b_count > 0
    ans += last_a_count > 0
    ans += max(min(first_b_count - 1, last_a_count - 1), 0)
else:
    ans += min(first_b_count , last_a_count )

print(ans)

Solution (Python):
n = int(input())
ab_num = 0
a_num = 0
b_num = 0
double = 0
for _ in range(n):
    s = input()
    ab_num += s.count("AB")
    if s[0] == "B":
        b_num += 1
    if s[-1] == "A":
        a_num += 1
    if (s[0] == "B") & (s[-1] == "A"):
        double += 1
ans = ab_num + min(a_num, b_num)
if (a_num == double) & (b_num == double):
    ans = ab_num + double - 1
if (a_num == 0) & (b_num == 0) & (double == 0):
    ans = ab_num
print(ans)

Solution (Python):
N = int(input())
ABc = 0
Ac = 0
Bc = 0
j = 0
for i in range(N):
	s = input()
	ABc += s.count("AB")
	if s[0] == "B":
		Bc += 1
	if s[-1] == "A":
		Ac += 1
	if s[0] == "B" and s[-1] == "A":
		j += 1

if Ac == Bc and Bc == j:
	if j == 0:
		print(ABc)
	else:
		print(ABc + Ac - 1)
else:
	print(ABc + min(Ac, Bc))

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

ans = 0   

cnt1 = 0  
cnt2 = 0  
cnt3 = 0  
for _ in range(N):
    s = input().strip()
    ans += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A': cnt1 += 1
    elif s[-1] == 'A': cnt2 += 1
    elif s[0] == 'B':  cnt3 += 1


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

print(ans)

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

n_AB = sum([s.count("AB") for s in S])
n_endA = 0
n_beginB = 0
flg = True

for s in S:
    if s[0] == 'B': n_beginB += 1
    if s[-1] == 'A': n_endA += 1
    if (s[0] == 'B') ^ (s[-1] == 'A'):
        flg = False
        
n_joined =  min(n_endA, n_beginB) - flg

print(n_AB + max(0, n_joined))

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

endwithA = 0
startwithB = 0
BandA = 0
ABCount = 0
ans = 0

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

    if s[0] == "B":
        if s[-1] == "A":
            BandA += 1
        else:
            startwithB += 1
    elif s[-1] == "A":
        endwithA += 1

    for index in range(len(s)):
        if index == 0:
            continue
        elif s[index-1] == "A" and s[index] == "B":
            ABCount += 1


if BandA > 0:
    if startwithB > 0:
        ans += 1
        startwithB -= 1
    if endwithA > 0:
        ans += 1
        endwithA -= 1
    ans += BandA - 1

ans += min(startwithB,endwithA)
ans += ABCount

print(ans)

Solution (Python):
N = int(input())
ss = [input() for _ in range(N)]
cnt = 0
ba = 0
b = 0
a = 0
o = 0
import re
for s in ss:
    cnt += len(re.findall('AB', s))
    if s[-1] == 'A' and s[0] == 'B':
        ba += 1
    elif s[-1] == 'A':
        a += 1
    elif s[0] == 'B':
        b += 1
    else:
        o += 1

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

print(cnt)

Solution (Python):
n = int(input())
ss = [input() for _ in range(n)]
ans = bsa = bs = sa = 0
for s in ss:
    ans += s.count("AB")
    if s[0] == "B":
        if s[-1] == "A":
            bsa += 1
        else:
            bs += 1
    elif s[-1] == "A":
        sa += 1
if bsa>0:
    ans+=bsa-1
    if bs>0:
        ans+=1
        bs-=1
    if sa>0:
        ans+=1
        sa-=1
ans+=min(bs,sa)
print(ans)

Solution (Python):



import sys
from collections import deque, Counter
import bisect
import math
from itertools import accumulate, product, permutations, combinations, groupby
from fractions import gcd 
import heapq
sys.setrecursionlimit(10**6)







n = int(input())
s = [input() for j in range(n)] 
ans = 0
ba = 0
bc = 0
ca = 0
cc = 0
for ss in s:
    if ss[0]=="B" and ss[-1]=="A":
        ba += 1
    elif ss[0]=="B":
        bc += 1
    elif ss[-1]=="A":
        ca += 1
    else:
        cc += 1
    for i in range(len(ss)-1):
        if ss[i] == "A" and ss[i+1] == "B":
            ans +=1

if bc==0 and ca == 0:
    ans += max(ba - 1,0)
else:
    ans += min(bc,ca) + ba
    
print(ans)

Solution (Python):
n = int(input())
slist = [input().strip() for _ in range(n)]

ea, sb = 0, 0
ans = 0
sd = {(0, 1): 0, (1, 0): 0, (1, 1): 0}
for s in slist:
  for prevs, _s in zip(s, s[1:]):
    if prevs + _s == 'AB':
      ans += 1
  if s[0] == 'B' and s[-1] == 'A':
    sd[(1, 1)] += 1
  elif s[0] == 'B':
    sd[(0, 1)] += 1
  elif s[-1] == 'A':
    sd[(1, 0)] += 1

if sd[(0, 1)] > 0 and sd[(1, 1)] > 0 and sd[(1, 0)] > 0:
  sd[(0, 1)] -= 1
  sd[(1, 0)] -= 1
  ans += sd[(1, 1)] + 1
elif sd[(0, 1)] > 0 and sd[(1, 1)] > 0 and sd[(1, 0)] == 0:
  sd[(0, 1)] -= 1
  ans += sd[(1, 1)]
elif sd[(0, 1)] == 0 and sd[(1, 1)] > 0 and sd[(1, 0)] > 0:
  sd[(1, 0)] -= 1
  ans += sd[(1, 1)]
elif sd[(0, 1)] == 0 and sd[(1, 0)] == 0:
  if sd[(1, 1)] > 0:
    ans += sd[(1, 1)] - 1

print(ans + min(sd[(1, 0)], sd[(0, 1)]))

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

ans = 0
start_b = 0
end_a = 0
ab = 0

for i in range(n):
    for j in range(len(S) - 1):
        if S[i][j:j+2] == 'AB':
            ans += 1

    if S[i][0] == 'B' and S[i][-1] == 'A':
        ab += 1
        continue 
    if S[i][0] == 'B':
        start_b += 1
    if S[i][-1] == 'A':
        end_a += 1
    

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

print(ans)

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

ab = 0
b_a = 0
b_ = 0
_a = 0
for i in range(N):
  ab += s[i].count('AB')
  if s[i][0] == 'B':
    if s[i][-1] == 'A':
      b_a += 1
    else:
      b_ += 1
  elif s[i][-1] == 'A':
    _a += 1
if b_a == 0:
  print(ab + min(b_, _a))
else:
  ans = ab + b_a - 1 + min(b_ - 1, _a - 1) + 2
  if b_ == 0 and _a == 0:
    ans -= 1
  print(ans)

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

elif a < b:
    res += a
    res += ab
else:
    res += b
    res += ab
print(res)

Solution (Python):
N = int(input())
ss = list(input() for _ in range(N))
ans = 0
a_end = 0
b_start = 0
both = 0
for si in ss:
    ans += si.count("AB")
    if si[0]=="B" and si[-1]=="A":
        both += 1
    elif si[0]=="B":
        b_start += 1
    elif si[-1]=="A":
        a_end += 1

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

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

res = 0
bhogea = 0
bhoge = 0
hogea = 0

for i in range(N):
    s = input()
    res += s.count('AB')
    if s[0] == 'B' and s[-1:] == 'A':
        bhogea += 1
    elif s[0] == 'B':
        bhoge += 1
    elif s[-1:] == 'A':
        hogea += 1

res = res + max(0, bhogea - 1)

if bhogea != 0:
    if bhoge != 0:
        bhoge = bhoge - 1
        res += 1
    if hogea != 0:
        hogea = hogea - 1
        res += 1

res = res + min(bhoge, hogea)

print(res)

Solution (Python):
import re
from collections import defaultdict
n = int(input())
ss = [input() for i in range(n)]

cnt = 0
for s in ss:
  cnt += len(re.findall(r'AB', s))



headtail = defaultdict(int)
for s in ss:
  if re.search('^B', s) and re.search('A$', s):
    headtail['ba'] += 1
  elif re.search('^B', s):
    headtail['b'] += 1
  elif re.search('A$', s):
    headtail['a'] += 1


cnt_connect = 0

if headtail['ba'] > 0:
  cnt_connect = headtail['ba'] - 1
  if headtail['a'] > 0:
    headtail['a'] -= 1
    cnt_connect += 1
  if headtail['b'] > 0:
    headtail['b'] -= 1
    cnt_connect += 1
cnt_connect += min([headtail['a'], headtail['b']])



cnt = cnt + cnt_connect

print(cnt)

Solution (Python):
N = int(input())
s = [input() for i in range(N)]
ans = 0
start = 0
end = 0
onaji = 0
hiku = 0
for i in s:
    if i[0]=="B":
        start += 1
    if i[-1]=="A":
        end += 1
    if i[0]=="B" and i[-1]=="A":
        onaji += 1
    if i[0]=="B" and i[-1]!="A":
        hiku += 1
    if i[0]!="B" and i[-1]=="A":
        hiku += 1
    for j in range(len(i)-1):
        if i[j]=="A":
            if i[j+1]=="B":
                ans += 1

if onaji>0 and hiku==0:
    print(ans+min(start, end)-1)
else:
    print(ans+min(start, end))

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

bstart, aend = 0, 0
doubleend = 0
ab = 0
for item in s:
    if item[0] == "B" and item[-1] == "A":
        doubleend += 1
    else:
        if item[-1] == "A":
            aend += 1
        if item[0] == "B":
            bstart += 1
    ab += item.count("AB")

ab += max(doubleend - 1, 0)
n -= (doubleend - 1)
if bstart > 0 and doubleend > 0:
    ab += 1
    bstart -= 1
    n -= 1
if aend > 0 and doubleend > 0:
    ab += 1
    aend -= 1
    n -= 1
ab += min(aend, bstart, n-1) 
print(ab)

Solution (Python):

import sys
from collections.abc import Iterable
from math import *
from itertools import *
from collections import *
from functools import *
from operator import *
try:
    from math import gcd
except Exception:
    from fractions import gcd


def solve(N: int, s: "List[str]"):
    hb = 0
    ta = 0
    hbta = 0
    ab = 0
    for ss in s:
        hb += 1 if (ss[0] == 'B' and ss[-1] != 'A') else 0
        ta += 1 if (ss[0] != 'B' and ss[-1] == 'A') else 0
        hbta += 1 if (ss[0] == 'B' and ss[-1] == 'A') else 0
        ab += ss.count('AB')

    if hb == 0 and 0 < hbta:
        hb += 1
        hbta -= 1
    if ta == 0 and 0 < hbta:
        ta += 1
        hbta -= 1

    if (0 < hb) and (0 < ta):
        ab += hbta + 1
        hb -= 1
        ta -= 1
    ab += min(hb, ta)
    return ab


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    s = [ next(tokens) for _ in range(N) ]  
    result = solve(N, s)
    if isinstance(result, Iterable):
        result = '\n'.join([str(v) for v in result])
    print(result)

if __name__ == '__main__':
    main()

Solution (Python):
ri = lambda: int(input())
rl = lambda: list(map(int,input().split()))
rr = lambda N: [ri() for _ in range(N)]
YN = lambda b: print('YES') if b else print('NO')
yn = lambda b: print('Yes') if b else print('No')
OE = lambda x: print('Odd') if x%2 else print('Even')
INF = 10**18

N=ri()
S = [0]*N
ans = 0
a = 0
b = 0
ab = 0
for i in range(N):
    S[i] = input()
for i in range(N):
    s_ = S[i]
    ans += s_.count('AB')
    if s_[0]=='B': b+=1
    if s_[-1]=='A': a+=1
    if s_[0]=='B' and s_[-1]=='A': ab+=1

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

print(ans)

Solution (Python):

def main():
    buf = input()
    N = int(buf)
    s = []
    for i in range(N):
        buf = input()
        s.append(buf)
    ab_count = 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':
                ab_count += 1
    A_count = 0
    B_count = 0
    BA_count = 0
    for i in range(N):
        if s[i][-1] == 'A' and s[i][0] == 'B':
            BA_count += 1
        elif s[i][-1] == 'A':
            A_count += 1
        elif s[i][0] == 'B':
            B_count += 1
    
    ab_count += max(0, BA_count - 1)
    
    if BA_count > 0 and A_count > 0:
        A_count -= 1
        ab_count += 1
    if BA_count > 0 and B_count > 0:
        B_count -= 1
        ab_count += 1
    
    ab_count += min(B_count, A_count)
    print(ab_count)


if __name__ == '__main__':
    main()

Solution (Python):
def main():
    N = int(input())
    ends_A = 0
    starts_B = 0
    B_A = 0
    include_AB = 0
    for i in range(N):
        s = input()
        
        
        if s[-1] == "A" and s[0] == "B":
            B_A += 1
        elif s[-1] == "A":
            ends_A += 1
        elif s[0] == "B":
            starts_B += 1

        aflag = 0
        for c in s:
            if aflag and c == "B":
                include_AB += 1
            if c == "A":
                aflag = True
            else:
                aflag = False
    if B_A != 0 and ends_A == 0 and starts_B == 0:
        print(B_A - 1 + include_AB)
    else:
        print(min(ends_A+B_A, starts_B+B_A) + include_AB)
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

            
            
if __name__ == "__main__":
    main()

Solution (Python):
n = int(input())
s = [input() for i in range(n)]
ans = 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":
            ans += 1

cnt_A = 0
cnt_B = 0
cnt_BA = 0

for i in range(n):
    if s[i][0] == "B" and s[i][-1] == "A":
        cnt_BA += 1
    elif s[i][0] == "B" and s[i][-1] != "A":
        cnt_B += 1
    elif s[i][0] != "B" and s[i][-1] == "A":
        cnt_A += 1 
ans += max(cnt_BA - 1, 0)
if cnt_BA > 0 and cnt_A > 0:
    ans += 1
    cnt_A -= 1
if cnt_BA > 0 and cnt_B > 0:
    ans += 1
    cnt_B -= 1
ans += min(cnt_A, cnt_B)
print(ans)

Solution (Python):
n = int(input())
s = [input() for i in range(n)]
ss = ""
ans = 0
t1, t2, t3 = 0, 0, 0
for e in s:
  ans += e.count("AB")
  if e[0] == "B" and e[-1] == "A":
    t3 += 1
  elif e[0] == "B":
    t1 += 1
  elif e[-1] == "A":
    t2 += 1
if t3:
  ans += t3-1
if t3 and t1:
  t1 -= 1
  ans += 1
if t3 and t2:
  t2 -= 1
  ans += 1
ans += max(0, min(t1, t2))
print(ans)

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

a = 0
b = 0
a_b = 0

for s in S:
    if s[-1] == "A" and s[0] == "B":
        a_b += 1
    elif s[-1] == "A":
        a += 1
    elif s[0] == "B":
        b += 1

ans = 0
if a_b > 0:
    ans += a_b - 1
    if a > 0:
        ans += 1
        a -= 1
    if b > 0:
        ans += 1
        b -= 1

ans += min(a,b)

for line in S:
    for i in range(len(line)-1):
        if (line[i],line[i+1]) == ("A","B"):
            ans += 1
print(ans)

Solution (Python):
N = int(input())
ans = n_BA = n_A = n_B = n_others = 0
for i in range(N):
    s = input()
    ans += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        n_BA += 1
    elif s[0] == 'B':
        n_B += 1
    elif s[-1] == 'A':
        n_A += 1
    else:
        n_others += 1

if n_BA >= 1:
    ans += n_BA - 1
    if n_A >= 1:
        n_A -= 1
        ans += 1
    if n_B >= 1:
        n_B -= 1
        ans += 1
ans += min(n_A, n_B)
print(ans)

Solution (Python):
n = int(input())
str_ab = 0
top_b = 0
bottom_a = 0
tbba = 0
for i in range(n):
    s = input()
    str_ab += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        tbba += 1
    elif s[0] == 'B':
        top_b += 1
    elif s[-1] == 'A':
        bottom_a += 1

if tbba == 0:
    ans = min(top_b, bottom_a) + str_ab
else:
    if top_b > 0 and bottom_a > 0:
        ans = str_ab + tbba - 1 + 2 + min(top_b, bottom_a) - 1
    else :
        if top_b > 0 or bottom_a > 0:
            ans = str_ab + tbba - 1 + 1
        else :
            ans = str_ab + tbba - 1

print(ans)

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

count = 0
for i in range(n):
    for j in range(len(s[i])-1):
        if s[i][j:j+2] == "AB":
            count += 1
a_end = 0
b_start = 0
both = 0
for i in range(n):
    if s[i][0] == "B":
        if s[i][-1] == "A":
            both += 1
        else:
            b_start += 1
    elif s[i][-1] == "A":
        a_end += 1
if a_end == 0 and b_start == 0:
    count += max(0,(both-1))
else:
    count += (both + min(a_end, b_start))
print(count)

Solution (Python):
n=int(input())
s=[input() for i in range(n)]
b_b=0
e_a=0
ba=0
ab=0
for i in range(n):
    for j in range(len(s[i])-1):
        if s[i][j:j+2]=='AB':
            ab+=1
    if s[i][0]=='B' and s[i][-1]=='A':
        ba+=1
    elif s[i][0]=='B':
        b_b+=1
    elif s[i][-1]=='A':
        e_a+=1
if ba>0:
    ab+=ba-1
    if e_a>0:
        b_b+=1
    if b_b>0:
        e_a+=1
print(ab+min(b_b,e_a))

Solution (Python):
import math
N=int(input())
ans=0
a,b=0,0
tmp=0
for i in range(N):
    s=input()
    if s[0]=="B": b+=1
    if s[-1]=="A": a+=1
    if a!=b: tmp=1
    ans+=s.count("AB")


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

Solution (Python):
N = int(input())
S = [input() for k in range(N)]
ans = 0
for s in S:
    ans += s.count("AB")


C = [[0,0] for k in range(N)]
for k in range(N):
    if S[k][0] == "B":
        C[k][1] = 1
    if S[k][-1] == "A":
        C[k][0] = 1
p = 0
q = 0
r = 0
for k in range(N):
    if C[k] == [0, 1]:
        p += 1
    elif C[k] == [1, 1]:
        q += 1
    elif C[k] == [1, 0]:
        r += 1
if p >= 1 and r >= 1 and q >= 1:
    print(ans + q+1 + min(p-1,r-1))
elif (p>=1 and r==0 and q>=1) or (p==0 and r>=1 and q>=1):
    print(ans + q)
elif p >= 1 and r >= 1 and q == 0:
    print(ans + min(p,r))
elif p == 0 and r == 0 and q >= 1:
    print(ans + q-1)
else:
    print(ans)