Problem:
 Score : 400 points    Problem Statement Snuke has N strings. The i -th string is s_i .  Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.      Constraints  1 \leq N \leq 10^{4}  2 \leq |s_i| \leq 10  s_i consists of uppercase English letters.         Input Input is given from Standard Input in the following format:  N  s_1  \vdots  s_N       Output Print the answer.        Sample Input 1 3
ABCA
XBAZ
BAD      Sample Output 1 2  For example, if we concatenate ABCA , BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB .       Sample Input 2 9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA      Sample Output 2 4       Sample Input 3 7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA      Sample Output 3 4

Solution (Python):
import sys
rr = lambda: sys.stdin.readline().strip()
ri = lambda: int(rr())
rs = lambda: [int(_) for _ in rr().split()]

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

a = 0
b = 0
c = 0
cnt = 0
for s in S:
    f = False
    for si in s:
        if not f:
            if si == 'A':
                f = True
        else:
            if si != 'A':
                f = False
            if si == 'B':
                cnt += 1
    if s[-1] == 'A':
        if s[0] == 'B':
            c += 1
        else:
            a += 1
    elif s[0] == 'B':
        b += 1

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

print(cnt)

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

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

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

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

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


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

simples = ''

a_flag = False

bias = 0
for i in range(N):
    simples += s[i]
    if s[i][-1]=="A" and s[i][0]=="B":
        if a_flag:
            bias += 1
        a_flag = True
        ba += 1
    elif s[i][-1]=="A":
        a_flag = True
        a += 1
    elif s[i][0]=="B":
        if a_flag:
            bias += 1
            a_flag = False
        b += 1
    else:
        a_flag = False
        continue

ans += simples.count("AB") - bias
if a>0 or b > 0:
    ans += ba
    ans += min(a,b)

if a==0 and b == 0:
    if ba > 1:
        ans += ba-1

print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 5)

N = int(input())
right_A = 0
left_B = 0
B_to_A = 0
AB_count = 0

for _ in range(N):
    target = input()
    AB_count += target.count('AB')
    if target[0] == 'B' and target[-1] == 'A':
        B_to_A += 1
    elif target[0] == 'B':
        left_B += 1
    elif target[-1] == 'A':
        right_A += 1

def recursive(x, y, z):
    if z == 0:
        return min(x, y)
    elif x == y == 0:
        return z - 1
    else:
        return recursive(x, y, z-1) + 1

print(recursive(right_A, left_B, B_to_A) + AB_count)

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

def countAB(str):
    count = 0
    for i in range(len(str)-1):
        if (str[i] == 'A') & (str[i+1] == 'B'):
            count += 1
    return(count)

def countRest(x, y, z):
    if(x > 0) | (y > 0):
        count = z + min(x, y)
    else:
        if(z > 1):
            count = z - 1
        else:
            count = 0
    return(count)

count = 0
count_bxa = 0
count_xa = 0
count_bx = 0
for s in s_list:
    count += countAB(s)
    if ((s[-1] == 'A') & (s[0] == 'B')):
        count_bxa += 1
    elif (s[-1] == 'A'):
        count_xa += 1
    elif (s[0] == 'B'):
        count_bx += 1

print(count + countRest(count_xa, count_bx, count_bxa))

Solution (Python):
N = int(input())
left, right, both = 0, 0, 0
ans = 0
for i in range(N):
    s = input()
    if s[0] == "B":
        if s[-1] == "A":
            both += 1
        else:
            left += 1
    elif s[-1] == "A":
        right += 1
    for j in range(len(s) - 1):
        if s[j] == "A" and s[j + 1] == "B":
            ans += 1


if min(left, right) >= 1:
    bonus = min(left, right) + both

elif max(left, right) == 0:
    bonus = max(both - 1, 0)

else:
    bonus = both

print(ans + bonus)

Solution (Python):
n = int(input())
lis = [input() for _ in range(n)]
cnt = sum([l.count('AB') for l in lis])
ab_cnt = sum([l[-1] == 'A' and l[0] == 'B' for l in lis])
a_cnt = sum([l[-1] == 'A' for l in lis]) - ab_cnt
b_cnt = sum([l[0] == 'B' for l in lis]) - ab_cnt
if ab_cnt:
  cnt += ab_cnt - 1
  if a_cnt or b_cnt:
    a_cnt += 1
    b_cnt += 1
print(cnt + min(a_cnt, b_cnt))

Solution (Python):


def solve():
    NAB, NBA, NB_, N_A = 0, 0, 0, 0
    for _ in range(int(input())):
        S = input()
        NAB += S.replace('AB', '-').count('-')
        b, a = S.startswith('B'), S.endswith('A')
        NBA += (b and a)
        NB_ += (b and (not a))
        N_A += ((not b) and a)
    res = NAB + max(NBA-1, 0) + (NB_>=1 and NBA>=1) + (N_A>=1 and NBA>=1) + max(min(NB_, N_A)-(NBA>=1), 0)

    return str(res)

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

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

XA = 0
BX = 0
BXA = 0
cnt = 0
for Si in S:
    cnt += Si.count("AB")

    tp = (Si[0] == "B")*1 + (Si[-1] == "A")*2
    if tp == 1:
        BX += 1
    elif tp == 2:
        XA += 1
    elif tp == 3:
        BXA += 1

if BXA > 0:
    cnt += BXA - 1
    BXA = 1

if BXA > 0:
    if BX > 0:
        cnt += 1
        BX -= 1
    if XA > 0:
        cnt += 1
        XA -= 1

pair = min(BX, XA)
if pair > 0:
    cnt += pair
    BX -= pair
    XA -= pair


print(cnt)

Solution (Python):
N = int(input())
A=0
B=0
BA=0
ans=0
for i in range(N):
  s = input()
  last = len(s)-1
  ans += s.count('AB')
  if s[0]=='B' and s[last]=='A':
    A+=1
    B+=1
    BA+=1
  elif s[0]=='B':
    B+=1
  elif s[last]=='A':
    A+=1
ans += min(A,B)
if A==B and B==BA and A!=0:
  ans-=1
print(ans)

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

Solution (Python):
a = int(input())
s = 0
A=B=AB=0

d = {"A":0,"B":0}
for i in range(a):
    t = input()
    s+=t.count("AB")
    if t[0]=="B" and t[-1]=="A":AB+=1
    elif t[0]=="B":B+=1
    elif t[-1]=="A":A+=1
res = 0
if A==0 and B == 0 and AB >0:
    res = AB-1
elif A==0 and B == 0:
    res = 0 
elif A==1 and B == 0:
    res = AB
elif A==0 and B ==1:
    res = AB
else:
    res = AB+1 + min(A-1,B-1)
print(res+s)

Solution (Python):
import sys

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

N = int(inp())
inAB = 0
sB = 0
eA = 0
both = 0
for _ in range(N):
  s = inp()
  inAB += s.count('AB')
  if s[0] == 'B' and s[-1] == 'A':
    both += 1
    continue
  if s[0] == 'B':
    sB += 1
  if s[-1] == 'A':
    eA += 1

pair = min(eA, sB)
if sB > 0 or eA > 0:
  ans = both + pair
else:
  ans = both - 1
print(inAB + max(ans, 0))

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

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

Solution (Python):
n=int(input())
ans=0
d={"a":0,"b":0,"w":0}
for i in range(n):
    s=input()
    if s[0]=="B" and s[-1]=="A": d["w"]+=1
    elif s[0]=="B" : d["b"]+=1
    elif s[-1]=="A" : d["a"]+=1
    ans+=s.count("AB")
if d["a"]==0 and d["w"]>0:
    d["a"]=1
    d["w"]-=1
if d["w"]>0:
    ans+=d["w"]
    d["w"]=0
    d["a"]-=1
    if d["b"]>0:
        ans+=1
        d["b"]-=1
ans+=max(0,min(d["a"],d["b"]))
print(ans)

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

N = INT()
num_either = 0
num_A = 0
num_B = 0

count = 0
for _ in range(N):
	s = input()
	if s[-1] == "A" and s[0] == "B":
		num_either += 1
	elif s[-1] == "A":
		num_A += 1
	elif s[0] == "B":
		num_B += 1

	for i, char in enumerate(s):
		if i == len(s)-1:
			break
		if s[i] == "A" and s[i+1] == "B":
			count += 1

if num_either >= 2:
	count += num_either-1
	num_either = 1
if num_A == 0 and num_B == 0:
	print(count)
else:
	if num_either == 1:
		count += min(num_A, num_B)+1
		print(count)
	else:
		count += min(num_A, num_B)
		print(count)

Solution (Python):
N=int(input())
both=0
one_A=0
one_B=0
sum=0
for i in range(N):
    S=list(input())
    if S[0]=='B' and S[len(S)-1]=='A':
        both+=1
    elif S[0]=='B':
        one_B+=1
    elif S[len(S)-1]=='A':
        one_A+=1
    for i in range(1,len(S)-1):
        if  S[i-1]=='A'and S[i]=='B':
            sum+=1
if both>0:
    sum+=(both-1)
    if one_A>0:
        sum+=1
        one_A-=1
    if one_B>0:
        sum+=1
        one_B-=1
    if one_A>one_B:
        sum+=one_B
    else:
        sum+=one_A
else:
    if one_A>one_B:
        sum+=one_B
    else:
        sum+=one_A
print(sum)

Solution (Python):
n=int(input())
s=[input() for _ in range(n)]
a=[]
b=[]
ab=[]
c=[]
for t in s:
    if t[0]=="B" and t[-1]=="A":
        ab.append(t)
    elif t[-1]=="A":
        a.append(t)
    elif t[0]=="B":
        b.append(t)
    else:
        c.append(t)
        
res=[]
ta,tb=0,0
if len(a)>0:
    res.append(a[ta])
    ta+=1
for t in ab:
    res.append(t)
if len(b)>0:
    res.append(b[tb])
    tb+=1

while(len(a)>ta and len(b)>tb):
    res.append(a[ta])
    res.append(b[tb])
    ta+=1
    tb+=1
for i in range(ta,len(a)):
    res.append(a[i])
for i in range(tb,len(b)):
    res.append(b[i])

for t in c:
    res.append(t)
ans="".join(res)
j= ans[0]=="A"
count=0
for i in range(1,len(ans)):
    if j:
        if ans[i]=="A":
            j=True
        elif ans[i]=="B":
            j=False
            count+=1
        else:
            j=False
    else:
        if ans[i]=="A":
            j=True
        else:
            j=False
print(count)

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

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

n = ni()
s = [ns() for _ in range(n)]

ans = 0

x = y = z = 0

for si in s:
    
    ans += si.count('AB')

    
    if si[:1] == 'B' and si[-1:] == 'A':
        z += 1

    
    elif si[-1:] == 'A':
        x += 1

    
    elif si[:1] == 'B':
        y += 1

if z <= x and z <= y:
    ans += 2*z
    ans += min(x,y) - z

else:
    ans += min(z, x)
    ans += min(z, y)

    if z >= x and z >= y:
        if x == 0 and y == 0:
            ans += z-1
        else:
            ans += z - max(x,y)

print(ans)

Solution (Python):
def main():
    N = int(input())
    strings = []
    for i in range(N):
        strings.append(input())
    
    ab = 0
    back_a = 0
    front_b = 0
    back_a_front_b = 0
    others = 0
    for i in strings:
        tmp = i
        ret = tmp.find("AB")
        while ret>=0:
            ab += 1
            tmp = tmp[ret+1:]
            ret = tmp.find("AB")
        
        if i[0] =="B" and i[-1]=="A":
            back_a_front_b += 1
        elif i[0] == "B":
            front_b += 1
        elif i[-1] == "A":
            back_a += 1
        else:
            others += 1

    if back_a_front_b == 0:
        print(ab + min([front_b,back_a]))
    elif back_a_front_b == N:
        print(ab + back_a_front_b -1)
    elif  min([front_b,back_a]) > 0:
        print(ab + back_a_front_b + 1 + min([front_b-1,back_a-1]))
    else:
        if back_a == 0 and front_b == 0:
            print(ab + max([back_a_front_b -1, 0]))
        elif back_a == 1 and front_b == 1:
            print(ab + back_a_front_b + 1)
        else:
            print(ab + back_a_front_b)

    
    
    
    

if __name__ == "__main__":
    main()

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

tail_a_num = 0
head_b_num = 0
both_num = 0
cnt = 0
for i in s:
  if i[0] == 'B':
    head_b_num += 1
  if i[-1] == 'A':
    tail_a_num += 1
  if i[0] == 'B' and i[-1] == 'A':
    both_num += 1
  cnt += i.count('AB')

if both_num > 0:
  cnt += both_num - 1
  head_b_num -= both_num
  tail_a_num -= both_num
  if head_b_num > 0:
    cnt += 1
    head_b_num -= 1
  if tail_a_num > 0:
    cnt += 1
    tail_a_num -= 1

cnt += min(head_b_num,tail_a_num)
  
print(cnt)

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

if N == 1:
    print(S[0].count("AB"))
    quit()

ba, ab, a, b = 0, 0, 0, 0
for s in S:
    if s[0] == "B" and s[-1] == "A":
        ba += 1
    elif s[0] == "B":
        b += 1
    elif s[-1] == "A":
        a += 1
    ab += s.count("AB")

if ba == 0:
    print(ab + min(a, b))
    quit()

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

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

sBA = [ss for ss in s if ss[0] == 'B' and ss[-1] == 'A']
sXA = [ss for ss in s if ss[0] != 'B' and ss[-1] == 'A']
sBX = [ss for ss in s if ss[0] == 'B' and ss[-1] != 'A']
sXX = [ss for ss in s if ss[0] != 'B' and ss[-1] != 'A']

ans = sXX
if sXA:
    ans.append(sXA.pop())
ans.extend(sBA)
while sXA or sBX:
    if sBX:
        ans.append(sBX.pop())
    if sXA:
        ans.append(sXA.pop())



ans = ''.join(ans)

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

print(nans)

Solution (Python):
x = int(input())
a = 0
b = 0
c = 0
f = 0
bun = []
for p in range(x):
    bun = input()
    if bun[0] == "B":
        b +=1
    if bun[len(bun)-1] == "A":
        a += 1
        if bun[0] == "B":
            f += 1
    for k in range(len(bun)-1):
        if bun[k] == "A":
            if bun[k+1] == "B":
                c += 1



if f == a:
    if a == b:
        if a > 0:
            a -= 1
if a < b:
    print(a+c)
else:
    print(b+c)

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

ans = 0
n_a = 0
n_b = 0
n_ab = 0
A_count = 0
B_count = 0
for i in range(N):
	ans += s[i].count("AB")
	if s[i][0] == "B" and s[i][-1] == "A":
		n_ab += 1
	if s[i][0] == "B" and s[i][-1] != "A":
		n_b += 1
	if s[i][0] != "B" and s[i][-1] == "A":
		n_a += 1
if n_ab == 0:
	ans += min(n_a,n_b)
if n_ab != 0:
	ans += n_ab-1
	if n_a == 0 and n_b == 0:
		ans += 0
	if n_a == 0 and n_b != 0:
		ans += 1
	if n_a != 0 and n_b == 0:
		ans += 1
	if n_a != 0 and n_b != 0:
		ans += 2+min(n_a-1,n_b-1)

print(ans)

Solution (Python):


def read_input():
    n = int(input())
    slist = []
    for i in range(n):
        slist.append(input())

    return n, slist

def submit():
    n, slist = read_input()

    ab_in = 0
    x_a = 0
    b_x = 0
    b_a = 0

    for s in slist:
        for s1,s2 in zip(s, s[1:]):
            if s1 == 'A' and s2 == 'B':
                ab_in += 1

        if s[0] == 'B' and s[-1] == 'A':
            b_a += 1
        elif s[0] == 'B':
            b_x += 1
        elif s[-1] == 'A':
            x_a += 1

    chain_ab = 0

    
    if b_a > 0:
        chain_ab += b_a - 1
        if x_a > 0:
            chain_ab += 1
            x_a -= 1

        if b_x > 0:
            chain_ab += 1
            b_x -= 1

    print(ab_in + chain_ab + min(x_a, b_x))


if __name__ == '__main__':
    submit()

Solution (Python):
N = int(input())
s_list = []
ans = 0

b_head_a_tail = 0
b_head = 0
a_tail = 0

for _ in range(N):
    string= input()
    if string[0] == "B":
        if string[-1] == "A":
            b_head_a_tail += 1
        else:
            b_head += 1
    elif string[-1] == "A":
        a_tail += 1
    if "AB" in string:
        ans += string.count("AB")
        
if b_head_a_tail > 0:
    if a_tail > 0:
        if b_head > 0:
            ans += b_head_a_tail  + min(a_tail, b_head) 
        else:
            ans += b_head_a_tail
    else:
        if b_head > 0:
            ans += b_head_a_tail
        else:
            ans += b_head_a_tail - 1
else:
    ans += min(a_tail, b_head) 
    
print(ans)

Solution (Python):
n = int(input())
s = [input() for _ in range(n)]
start_b = len([i for i in s if i[0] == "B" and i[-1] != "A"])
end_a = len([i for i in s if i[-1] == "A" and i[0] != "B"])
both = len([i for i in s if i[0] == "B" and i[-1] == "A"])
include_ab = sum([i.count("AB") for i in s])

if both:
  if end_a:
    if start_b:
      end_a -= 1
      start_b -= 1
      include_ab += (both+1)
    else:
      end_a -= 1
      include_ab += both
  else:
    if start_b:
      start_b -= 1
      include_ab += both
    else:
      include_ab += (both - 1)
print(include_ab + min(start_b,end_a))

Solution (Python):
import re

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

num_end_with_A = 0
num_start_with_B = 0
num_both = 0
num_inner_AB = 0

for ss in s:
    res = re.findall('AB', ss)
    if res:
        num_inner_AB += len(res)
    if ss[0] == 'B' and ss[-1] == 'A':
        num_both += 1
    elif ss[0] == 'B':
        num_start_with_B += 1
    elif ss[-1] == 'A':
        num_end_with_A += 1

if num_end_with_A == 0 and num_start_with_B == 0:
    print(num_inner_AB + max(num_both - 1, 0))
else:
    print(num_inner_AB + min(num_end_with_A, num_start_with_B) + num_both)

Solution (Python):
N = int(input())
S = []
for _ in range(N):
  S.append(input())
ans = 0
tailA, headB, b_a = 0, 0, 0
for s in S:
  ans += s.count('AB')
  h, t = s[0], s[-1]
  if h == 'B' and t != 'A':
    headB += 1
  elif h != 'B' and t == 'A':
    tailA += 1
  elif h == 'B' and t == 'A':
    b_a += 1
ans += min(tailA, headB)
if b_a > 0:
  ans += b_a - 1
  if tailA > 0 or headB > 0:
    ans += 1
print(ans)

Solution (Python):
import sys

readline = sys.stdin.readline

N = int(readline())
S_list = [readline().rstrip() for i in range(N)]

count = 0
head_B = 0
tail_A = 0
AxB = 0
for s in S_list:
    for i in range(len(s)):
        if s[i:i+2] == 'AB':
            count += 1
    if s[0] == 'B':
        head_B += 1
    if s[-1] == 'A':
        tail_A += 1
    if (s[0] == 'B') != (s[-1] == 'A'):
        AxB += 1

if head_B == tail_A:
    if AxB > 0:
        print(count + head_B)
    else:
        print(count + max(head_B - 1, 0))
else:
    print(count + min(head_B, tail_A))

Solution (Python):


def solve():
    N = int(input())
    ans = 0
    endA = 0
    startB = 0
    ryouhou = 0
    
    for i in range(N):
        s = input()
        if s[-1]=="A" and s[0]=="B":
            ryouhou += 1
        elif s[-1]=="A":
            endA += 1
        elif s[0]=="B":
            startB += 1
        
        ans += s.count("AB")
    

    if endA>=1 and startB>=1 and ryouhou>=1:
        ans += min(endA-1, startB-1)
        ans += ryouhou + 1
        print(ans)
        return
    elif ((endA>=1 and startB==0 and ryouhou>=1) or
          (endA==0 and startB>=1 and ryouhou>=1)):
        ans += ryouhou
        print(ans)
        return
    elif endA==0 and startB==0 and ryouhou>=1:
        ans += ryouhou-1
        print(ans)
        return
    else:
        
        ans += min(endA, startB)
        rest = abs(max(endA, startB) - min(endA, startB))
        
        ans += min(rest, ryouhou)
        rest = ryouhou - rest
        if rest <= 0:
            print(ans)
            return
        else:
            ans += rest//2
            print(ans)
            return

if __name__ == "__main__":
    solve()

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

Solution (Python):
n = int(input())
bb = 0
af = 0
ab = 0
p = 1
for i in range(n):
  s = input()
  l = len(s)
  if s[0] == "B":
    bb += 1
  if s[l - 1] == "A":
    af += 1
  if s[0] == "B" and s[l - 1] != "A":
    p = 0
  if s[0] != "B" and s[l - 1] == "A":
    p = 0
  for j in range(l - 1):
    if s[j] == "A":
      if s[j + 1] == "B":
        ab += 1
if af == bb:
  if af == 0:
    ans = ab
  else:
    ans = ab + af - p
else:
  ans = ab + min(af, bb)
print(ans)

Solution (Python):
def solve():
    ans = 0
    li = [0, 0, 0, 0]
    for _ in range(int(input())):
        s = input()
        ans += s.count("AB")
        flg = 0
        if s[0] == 'B':
            flg = 1
        if s[-1] == 'A':
            flg += 2
        li[flg] += 1
    if li[3] > 0:
        if li[1] > 0:
            ans += 1
            li[1] -= 1
        if li[2] > 0:
            ans += 1
            li[2] -= 1
        ans += li[3] - 1
    print(ans + min(li[1], li[2]))
solve()

Solution (Python):
N = int(input())
s = 0
t = 0
u = 0
v = 0
for i in range(N):
    m = input()
    u += m.count("AB")
    if m[0] == "B" and m[-1] == "A":
        v += 1
    else:
        if m[0] == "B":
            s += 1
        if m[-1] == "A":
            t += 1
if s == 0 and t == 0 and v != 0:
    u += v - 1
    print(u)
elif s == 0 or t == 0:
    u += v
    print(u)
else: 
    u += min(s - 1, t - 1) + v + 1
    print(u)

Solution (Python):
import re
N = int(input())
S = [input() for i in range(N)]
nAB = sum(map(lambda x: x.count('AB'), S))
lastB = sum(map(lambda x: x[0] == 'B', S))
firstA = sum(map(lambda x: x[-1] == 'A', S))
matchAB = sum(map(lambda x: x[0] == 'B' and x[-1] == 'A', S))
if min(lastB, firstA) == 0:
    print(nAB)
elif lastB == firstA and matchAB - min(lastB, firstA) == 0:
    print(nAB+min(lastB, firstA)-1)
elif matchAB - min(lastB, firstA) == 0:
    print(nAB+min(lastB, firstA))
else:
    print(nAB+min(lastB, firstA))

Solution (Python):

import sys


def solve(N: int, s: "List[str]"):
    count_AB = 0
    count_endswith_A = 0
    count_startswith_B = 0
    count_BA = 0
    for ss in s:
        count_AB += ss.count('AB')
        if ss.endswith('A') and ss.startswith('B'):
            count_BA += 1
            continue
        if ss.endswith('A'):
            count_endswith_A += 1
        if ss.startswith('B'):
            count_startswith_B += 1
    count_pair = min(count_endswith_A, count_startswith_B)
    if count_pair > 0:
        print(count_AB + count_pair + count_BA)
    elif count_endswith_A > 0 or count_startswith_B > 0:
        print(count_AB + count_BA)
    elif count_BA > 0:
        print(count_AB + count_BA - 1)
    else:
        print(count_AB)
    return



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) ]  
    solve(N, s)

if __name__ == '__main__':
    main()

Solution (Python):
inpl = lambda: list(map(int,input().split()))
N = int(input())
ans = 0
BA  = [[0, 0], [0, 0]]
for i in range(N):
    s = input()
    ans += s.count('AB')
    h = 1 if s[0]=='B' else 0
    t = 1 if s[-1]=='A' else 0
    BA[h][t] += 1
if BA[1][0]==BA[0][1]==0 and BA[1][1]>0:
    ans += BA[1][1]-1
else:
    ans += min(BA[1][0],BA[0][1]) + BA[1][1]

print(ans)

Solution (Python):
N = int(input())
P = 0
K = 0
L = 0
ans = 0
for _ in range(N):
  s = input()
  lis = []
  for i in range(len(s) - 1):
    lis.append(s[i:i+2])
    num = lis.count("AB")
  ans += num
  if s[0] == "B" and s[-1] == "A":
    P += 1
  elif s[0] == "B":
    K += 1
  elif s[-1] == "A":
    L += 1
if P >= 1:
  ans += (P - 1)
  if K > 0 and L > 0:
    ans += 2
    ans += min(K -1, L - 1)
  elif K > 0 and L == 0:
    ans += 1
  elif K == 0 and L > 0:
    ans += 1
else:
  ans += min(K, L)
print(ans)

Solution (Python):
N = int(input())
S = [input() for _ in range(N)]
first_c = []
last_c = []
XA = 0
BA = 0
BX = 0

ans = 0

for s in S:
    first_c.append(s[0])
    last_c.append(s[len(s)-1])
    ans += s.count("AB")

for i in range(len(S)):
    if first_c[i] == "B" and last_c[i] == "A":
        BA += 1
    elif first_c[i] == "B" and last_c[i] != "A":
        BX += 1
    elif first_c[i] != "B" and last_c[i] == "A":
        XA += 1

if BX > 0 and XA > 0:
    ans += min(BX, XA) + BA
elif BX > 0 or XA > 0:
    ans += BA
elif BA > 1:
    ans += BA-1

print(ans)

Solution (Python):
N = int(input())
count=0
A = 0
B = 0
BA = 0
for i in range(N):
  s = input()
  exist = 0
  if (s[0] == 'B') and (s[-1] == 'A'):
    BA +=1
  elif s[0] == 'B':
    B+=1
  elif s[-1:] == 'A':
    A+=1
  for j in range(len(s)-1):
    if s[j:j+2] == "AB":
      count+=1


if BA > 1:
  count += BA - 1
if BA >0:
  if A > 0 :
    count +=1
    A-=1
  if B>0:
    count+=1
    B-=1
if A>B:
  count += B
else:
  count += A
print(count)

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

Solution (Python):
from collections import defaultdict
from string import ascii_uppercase
import sys, bisect, math
stdin = sys.stdin
read_int = lambda : list(map(int,stdin.readline().split()))
read_str = lambda : stdin.readline().rstrip()

N = read_int()[0]
S = [read_str() for _ in range(N)]

def solve():
    _a = 0
    b_ = 0
    ba = 0
    in_ab = 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: j + 2] == 'AB':
                in_ab += 1

    ans = 0
    if ba == 0:
        ans += in_ab + min(_a, b_)
        return ans
    ans += in_ab + max(ba - 1,0) + max(0, min(_a - 1, b_ - 1))
    
    if _a > 0: ans += 1
    if b_ > 0: ans += 1
    return ans

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

Solution (Python):

n = int(input())

cnt_ab = 0
cnt_ba = 0
cnt_last_a = 0
cnt_first_b = 0
for _ in range(n):
    s = input()
    cnt_ab += s.count("AB")

    b_flag, a_flag = False, False
    if s[0] == 'B':
        b_flag = True
    if s[-1] == 'A':
        a_flag = True

    if a_flag and b_flag:
        cnt_ba += 1
    elif b_flag:
        cnt_first_b += 1
    elif a_flag:
        cnt_last_a += 1

if cnt_ba >= 2:
    cnt_ab += cnt_ba - 1
    cnt_ba = 1

if cnt_ba == 1 and cnt_first_b >= 1 and cnt_last_a >= 1:
    cnt_ab += 2
    cnt_first_b -= 1
    cnt_last_a -= 1
elif cnt_ba == 1:
    if max(cnt_first_b, cnt_last_a) > 0:
        cnt_ab += 1

print(cnt_ab + min(cnt_first_b, cnt_last_a))

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

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

ans = 0
A_flag = 0
B_flag = 0
A_flag2 = 0
B_flag2 = 0

for i in range(N):
    S = input()
    ans += S.count('AB')

    if S[0] == 'B':
        B_flag += 1

    if S[-1] == 'A':
        A_flag += 1

    if S[0] != 'B' and S[-1] == 'A':
        A_flag2 = 1

    if S[0] == 'B' and S[-1] != 'A':
        B_flag2 = 1

if A_flag != B_flag:
    ans += min(A_flag,B_flag)
else:
    if A_flag+B_flag != 0:
        if A_flag2*B_flag2 == 0:
            ans += min(A_flag,B_flag) -1
        else:
            ans += min(A_flag,B_flag)
print(ans)

Solution (Python):
n = int(input())
S = []
ans = 0
a =0 
b = 0
both = 0
for _ in range(n):
    temp = input()
    ans += temp.count("AB")
    if temp[0] == "B" and temp[-1] == "A":
        both += 1
    elif temp[0] =="B":
        b += 1
    elif temp[-1] == "A":
        a += 1
if a==0 and b==0:
    print(ans+max(0,both-1))
elif a==0  or b == 0:
    print(ans + both if both > 0 else ans)
else:
    print(ans+min(a,b)+both)

Solution (Python):



def main():
    N = int(input())
    s_list = []
    for i in range(N):
        s_list.append(input().rstrip())

    ans = 0
    a_last = 0
    ab_count = 0
    b_start = 0
    for si in s_list:
        if si[0] == "B" and si[-1] == "A":
            ab_count += 1
        elif si[0] == "B":
            b_start += 1
        elif si[-1] == "A":
            a_last += 1

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

    if ab_count > 0:
        ans += ab_count - 1
        if a_last == 0 and b_start == 0:
            pass
        else:
            ans = ans + min(a_last, b_start) + 1
    else:
        ans = ans + min(a_last, b_start)
    
    print(ans)


if __name__ == "__main__":
    main()