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

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


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

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

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

endA = 0
startB = 0
both = 0
cntAB = 0
for i in range(n):
    s = input()
    for j in range(len(s)-1):
        if s[j]=='A' and s[j+1]=='B':
            cntAB+=1
    if s[0] == 'B':
        startB +=1
    if s[-1] == 'A':
        endA += 1
    if s[-1]=='A' and s[0] == 'B':
        both+=1

onlyA = endA - both
onlyB = startB - both

if both:
    cntAB += both -1
    if onlyA:
        cntAB += 1
        onlyA -= 1
    if onlyB:
        cntAB +=1
        onlyB -= 1
    cntAB += min(onlyA,onlyB)
else:
    cntAB += min(onlyA,onlyB)
print(cntAB)

Solution (Python):
n = int(input())
count = 0
na, nb, nab = 0, 0, 0
for _ in range(n):
    s = input().strip()
    if s[0] == 'B' and s[-1] == 'A':
        nab += 1
    elif s[0] == 'B':
        nb += 1
    elif s[-1] == 'A':
        na += 1

    for i in range(len(s) - 1):
        if s[i:i+2] == 'AB':
            count += 1

if nab > 0:
    count += (nab - 1)
    if na > 0:
        na -= 1
        count += 1
    if nb > 0:
        nb -= 1
        count += 1

    count += min(na, nb)
else:
    count += min(na, nb)

print(count)

Solution (Python):
n = int(input())
st = [input() for _ in range(n)]
count = 0
for s in st:
    count += s.count('AB')
first = 0
last = 0
both = 0
for s in st:
    if s[0] == 'B' and s[-1] == 'A':
        both += 1
    elif s[0] == 'B':
        first += 1
    elif s[-1] == 'A':
        last += 1
if first + last == 0 and both >= 1:
    print(count + both - 1)
else:
    print(count + min(first, last) + both)

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

A = 0
B = 0
AB = 0
Ans = 0

for i in s:
  if i[0] == "B" and i[-1] == "A":
    AB += 1
  elif i[0] == "B":
    B += 1
  elif i[-1] == "A":
    A += 1
  f = False
  for j in i:
    if j == "B" and f:
      Ans += 1
    if j == "A":
      f = True
    else:
      f = False

if AB != 0:
  Ans += AB - 1
  if A != 0:
    A -= 1
    Ans += 1
  if B != 0:
    B -= 1
    Ans += 1
Ans += min(A, B)

print(Ans)

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

count_a_last = 0
count_b_first = 0
coincide = True
internal = 0
for s in strings:
	internal += s.count("AB")

	if s[0] == "B" and s[-1] == "A":
		count_a_last += 1
		count_b_first += 1
	elif s[0] == "B":
		count_b_first += 1
		coincide = False
	elif s[-1] == "A":
		count_a_last += 1
		coincide = False

concat = min(count_a_last, count_b_first)
if concat > 0 and coincide :
	concat -= 1
print(internal + concat)

Solution (Python):
import sys
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()

def main():
    N = II()
    S = []
    for _ in range(N):
        S.append(SI())
    ans = 0
    BA = 0
    BX = 0
    XA = 0
    for s in S:
        if s[0] == 'B' and s[-1] == 'A':
            BA += 1
        elif s[0] == 'B':
            BX += 1
        elif s[-1] == 'A':
            XA += 1
        for i in range(len(s) - 1):
            if s[i] == 'A' and s[i+1] == 'B':
                ans += 1
    ans += min(BA + BX, BA + XA)
    if BX == 0 and XA == 0 and BA > 0:
        ans -= 1
    return ans

print(main())

Solution (Python):
import sys
range = xrange
input = raw_input

n = int(input())
S = [input() for _ in range(n)]

BA = []
BX = []
XX = []
XA = []
for s in S:
    if s[0] == 'B':
        if s[-1] == 'A':
            BA.append(s)
        else:
            BX.append(s)
    elif s[-1] == 'A':
        XA.append(s)
    else:
        XX.append(s)

picker = []
ends_with_A = False
while BA or BX or XX or XA:
    if not ends_with_A:
        X = XA or BA or XX or BX
    else:
        X = BA or BX or XX or XA
    picker.append(X.pop())
    if picker[-1][-1] == 'A':
        ends_with_A = True
    else:
        ends_with_A = False
print ''.join(picker).count('AB')

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

Solution (Python):

"""<https://github.com/cheran-senthil/PyRival>"""
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    _str = str
    str = lambda x=b"": x if type(x) is bytes else _str(x).encode()


def main():
    n = int(input())
    s = [input() for _ in range(n)]
    end_a = []
    start_b = []
    both = []
    other = []
    for si in s:
        if si[-1] == 'A':
            if si[0] == 'B':
                both.append(si)
            else:
                end_a.append(si)
        elif si[0] == 'B':
            start_b.append(si)
        else:
            other.append(si)

    res = ''.join(both)

    if start_b:
        res += start_b.pop()
    if end_a:
        res = end_a.pop() + res

    tmp = []
    while end_a and start_b:
        tmp.append(end_a.pop() + start_b.pop())

    res += ''.join(tmp) + ''.join(end_a) + ''.join(start_b) + ''.join(other)
    print(res.count('AB'))




BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._buffer = BytesIO()
        self._fd = file.fileno()
        self._writable = "x" in file.mode or "r" not in file.mode
        self.write = self._buffer.write if self._writable else None

    def read(self):
        if self._buffer.tell():
            return self._buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self._buffer.tell()
            self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
        self.newlines -= 1
        return self._buffer.readline()

    def flush(self):
        if self._writable:
            os.write(self._fd, self._buffer.getvalue())
            self._buffer.truncate(0), self._buffer.seek(0)


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()


sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")



if __name__ == "__main__":
    main()

Solution (Python):
N = int(input())
a = 0
b = 0
ab = 0
c = 0
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':
        c += 1
    for i in range(len(s) - 1):
        if s[i:i+2] == "AB":
            ab += 1
ans = ab + min(a, b)
if a == b and a == c and a > 0:
    ans -= 1
print(ans)

Solution (Python):
N=int(input())
S=[input() for i in range(N)]
a,b,ba=0,0,0
ans=0
for s in S:
  if s[0]=="B":
    if s[-1]=="A":
      ba+=1
    else:
      b+=1
  elif s[-1]=="A":
    a+=1
  for l in range(len(s)-1):
    if s[l:l+2]=="AB":
       ans+=1


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

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

a = 0
b = 0
ans = 0
c = 0

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

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

print(ans)

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

ht = []
h = []
t = []

cnt = 0

for i, ss in enumerate(s):
    cnt += ss.count('AB')

    a = ss[-1] == 'A'
    b = ss[0] == 'B'
    if a:
        if b:
            ht.append(i)
        else:
            t.append(i)
    else:
        if b:
            h.append(i)

len_h = len(h)
len_t = len(t)
len_ht = len(ht)

ans = cnt
if len_ht > 0:
    ans += len_ht - 1
    if len_t > 0:
        len_t -= 1
        ans += 1
    if len_h > 0:
        len_h -= 1
        ans += 1
ans += min(len_h, len_t)
print(ans)

Solution (Python):
N = int( input())
S = [ input() for _ in range(N)]
ans = 0
A = 0
B = 0
T = 0
for s in S:
    t = 0
    if s[0] == "B":
        B += 1
        t += 1
    if s[-1] == "A":
        A += 1
        t += 1
    if t == 2:
        T += 1
    for i in range( len(s)-1):
        if s[i] == "A" and s[i+1] == "B":
            ans += 1
if A == B:
    if A == 0:
        pass
    elif T == A:
        ans += A-1
    else:
        ans += min(A,B)
else:
    ans += min(A,B)
print(ans)

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

nb_na, b_na, nb_a, b_a = 0, 0, 0, 0
ans = 0
for _ in range(N):
    s = input()
    ans += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        b_a += 1
    elif s[0] == "B":
        b_na += 1
    elif s[-1] == "A":
        nb_a += 1
    else:
        nb_na += 1
if b_a > 0 and nb_a > 0:
    b_a += 1
    nb_a -= 1
if b_a > 0 and b_na > 0:
    b_a += 1
    b_na -= 1
ans += min(nb_a, b_na)

if b_a > 0:
    ans += b_a - 1

print(ans)

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

s = [input() for _ in range(n)]

cnt = sum(x.count("AB") for x in s)

cnt_a = sum(x[-1] == "A" for x in s)
cnt_b = sum(x[0] == "B" for x in s)

cnt_ab = sum(x[0] == "B" and x[-1] == "A" for x in s)

if cnt_a == cnt_b == cnt_ab > 0:
    print(cnt + cnt_a - 1)
else:
    print(cnt + min(cnt_a, cnt_b))

Solution (Python):
from collections import defaultdict
import sys,heapq,bisect,math,itertools,string,queue,datetime
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inpl(): return list(map(int, input().split()))
def inpl_str(): return list(input().split())

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

ans = 0
fb = 0
la = 0
dottimo = 0
for s in ss:
    L = len(s)
    flag1 = flag2 = False
    for i in range(L-1):
        if s[i:i+2] == 'AB':
            ans += 1

    if s[0] == 'B':
        fb += 1
        flag1 = True

    if s[-1] == 'A':
        la += 1
        flag2 = True

    if flag1 and flag2:
        dottimo += 1

if fb == 0:
    print(ans)
elif fb == la and fb == dottimo:
    print(ans+dottimo-1)
else:
    print(ans+min(la,fb))

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)


def main():
    n = I()
    a = [S() for _ in range(n)]
    ss = '-'
    r = 0
    ba = []
    ta = []
    tb = []
    for s in a:
        if s[0] == 'B':
            if s[-1] == 'A':
                ba.append(s)
            else:
                tb.append(s)
        elif s[-1] == 'A':
            ta.append(s)
        else:
            r += len(s.split('AB')) - 1

    while ba or ta or tb:
        if ss[-1] == 'A':
            if ba:
                ss += ba[-1]
                ba = ba[:-1]
            elif tb:
                ss += tb[-1]
                tb = tb[:-1]
            else:
                ss += ta[-1]
                ta = ta[:-1]
        else:
            if ta:
                ss += ta[-1]
                ta = ta[:-1]
            elif ba:
                ss += ba[-1]
                ba = ba[:-1]
            else:
                ss += tb[-1]
                tb = tb[:-1]
    

    return r + len(ss.split('AB')) - 1


print(main())

Solution (Python):
def makelist(n, m):
    return [[0 for _ in range(m)] for _ in range(n)]

N = int(input())

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


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

ans += min(a, b)
print(ans)

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

A=0
B=0
BA=0

ans = 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
  ans += s.count('AB')

if BA > 1:
  ans += BA-1
  BA = 1

if BA ==1:
  if A>=1:
    ans += 1
    BA=0
    A = A-1
  if B>=1:
    ans +=1
    BA=0
    B = B-1

if BA==0:
  ans += min(A,B)
  
print(ans)

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

a = 0
b = 0
ans = 0
ab = 0

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

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

print(ans)

Solution (Python):
import sys

n = int(input())
ans = 0
tail_a = 0
head_b = 0
both = 0
for s in sys.stdin:
    s = s.rstrip()
    ans += s.count('AB')
    if s[0] == 'B':
        if s[-1] == 'A':
            both += 1
        else:
            head_b += 1
    elif s[-1] == 'A':
        tail_a += 1
if both:
    ans += both - 1
    if tail_a:
        ans += 1
        tail_a -= 1
    if head_b:
        ans += 1
        head_b -= 1
ans += min(tail_a, head_b)
print(ans)

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

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

res = 0
BxA = 0
xxA = 0
Bxx = 0

for _ in range(N):
    s = list(input())
    for i in range(len(s) - 1):
        if s[i] + s[i + 1] == "AB":
            res += 1
    if s[0] == "B" and s[-1] == "A":
        BxA += 1
    elif s[0] == "B":
        Bxx += 1
    elif s[-1] == "A":
        xxA += 1

res_2 = 0
if xxA == 0 and Bxx == 0 and BxA != 0:
    res_2 = BxA - 1
else:
    res_2 = min(BxA + xxA, Bxx + BxA)

print(res + res_2)

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

Solution (Python):
n = int(input())
s = [input() for _ in range(n)]
t = []
res = 0
for c in s:
    t.append(c[0] + c[-1])
    res += c.count('AB')

a,b,ba = 0,0,0
for c in t:
    if c == 'BA':
        ba += 1
    elif c[0] == 'B':
        b += 1
    elif c[-1] == 'A':
        a += 1

if ba > 0:
    res += ba - 1
    if a > 0:
        res += 1
        a -= 1
    if b > 0:
        res += 1
        b -= 1

res += min(a, b)

print(res)

Solution (Python):
N=int(input())
s=[input() for i in range(N)]
a=[i.count("AB") for i in s]
X=[0 for i in range(N)]
Y=[0 for i in range(N)]
for i in range(N):
    if s[i][0]=="B":
        X[i]+=1
    if s[i][-1]=="A":
        Y[i]+=1
flag=0
tmp=0
for i in range(N):
    if (X[i]+Y[i])%2==1:
        flag=1
        break
    if (X[i]+Y[i]==2):
        tmp+=1
if flag==1:
    print(sum(a)+min(sum(X),sum(Y)))
else:
    if tmp==0:
        print(sum(a))
    else:
        print(sum(a)+tmp-1)

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

ans = 0
b_start = 0
a_end = 0
b_start_and_a_end = 0
for s in S:
    ans += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        b_start_and_a_end += 1
    elif s[0] == "B":
        b_start += 1
    elif s[-1] == "A":
        a_end += 1

ans += min(b_start, a_end)

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

print(ans)