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

ans = 0

stb_eda = 0
stb = 0
eda = 0

for si in s:
    stmp = "".join(si)
    ans += stmp.count("AB")
    if si[0] == "B" and si[-1] == "A":
        stb_eda += 1
    elif si[0] == "B":
        stb += 1
    elif si[-1] == "A":
        eda += 1

if stb >= eda:
    diff = min(stb - eda, stb_eda)
    eda += diff
    stb_eda -= diff

else:
    diff = min(eda - stb, stb_eda)
    stb += diff
    stb_eda -= diff


if eda > 0 or stb > 0:
    ans += min(eda, stb) + stb_eda
else:
    ans += min(eda, stb) + max(0, stb_eda-1)

print(ans)

Solution (Python):
n = int(input())
string_list = [ input() for i in range(n) ]
ans = 0
ab_list = [0, 0, 0]

for i in string_list:
    for j in range(len(i)-1):
        if i[j] == "A" and i[j+1] == "B":
            ans += 1
    if i[0] == "B" and i[-1] == "A":
        ab_list[0] += 1
    elif i[0] == "B":
        ab_list[1] += 1
    elif i[-1] == "A":
        ab_list[2] += 1

if ab_list[0] == 0:
    ans += min(ab_list[1], ab_list[2])
else:
    ans += ab_list[0] - 1
    if ab_list[1] > 0:
        ans += 1
        ab_list[1] -= 1
    if ab_list[2] > 0:
        ans += 1
        ab_list[2] -= 1
    ans += min(ab_list[1], ab_list[2])
print(ans)

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

count = 0
both = 0
forward = 0
backward = 0
for i in range(N):
    tmp = list(input())
    if tmp[0] == 'B' and tmp[-1] == 'A':
        both += 1
    elif tmp[0] == 'B' and tmp[-1] != 'A':
        forward += 1
    elif tmp[0] != 'B' and tmp[-1] == 'A':
        backward += 1
    for i in range(len(tmp) - 1):
        if tmp[i] == 'A' and tmp[i + 1] == 'B':
            count += 1






count += max(0, both - 1)
if both > 0:
    if forward > 0 and backward > 0: 
        forward -= 1
        backward -= 1
        count += 2
    elif forward > 0 and backward == 0: 
        count += 1
        forward -= 1
    elif forward == 0 and backward > 0: 
        count += 1
        backward -= 1
count += min(forward, backward)
print (count)

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

ans = 0
for ss in sss:
    ans += ss.count('AB')

num_A = numB_ = numBA = 0
for ss in sss:
    is_A = ss.endswith('A')
    isB_ = ss.startswith('B')
    if is_A:
        num_A += 1
    if isB_:
        numB_ += 1
    if is_A and isB_:
        numBA += 1

ans += min(num_A, numB_)
if num_A == numB_ == numBA and num_A > 0:
    ans -= 1

print(ans)

Solution (Python):



import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7

n = int(input())
_A = []
B_ = []
BA = []
cnt = 0
for _ in range(n):
    s = input()
    for i in range(len(s)-1):
        if s[i] == 'A' and s[i+1] == 'B':
            cnt += 1
    if s[0] != 'B' and s[-1] == 'A':
        _A.append(s)
    elif s[0] == 'B' and s[-1] != 'A':
        B_.append(s)
    elif s[0] == 'B' and s[-1] == 'A':
        BA.append(s)
a = len(_A)
b = len(B_)
ba = len(BA)
ans = cnt
if ba >= 1:
    if a + b > 0:
        ans += (ba-1) + min(a,b) + 1
    else:
        ans += ba - 1
else:
    ans += min(a,b)
print(ans)

Solution (Python):
class diverta2019C:
    def __init__(self):
        self.N = int(input())
        self.s = [input() for i in range(self.N)]
        self.ans = 0
    
    def solve(self):
        a, b, c = 0, 0, 0
        for i in range(self.N):
            if(self.s[i].count('AB')):
                self.ans += self.s[i].count('AB')
            if(self.s[i][-1] == 'A' and self.s[i][0] == 'B'):
                a += 1
            elif(self.s[i][0] == 'B'):
                b += 1
            elif(self.s[i][-1] == 'A'):
                c += 1
        if(a == 0):
            self.ans += min(b, c)
        elif(b + c > 0):
            self.ans += a + min(b, c)
        else:
            self.ans += a-1
        print(self.ans)

if __name__ == '__main__':
    problem = diverta2019C()
    problem.solve()

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

ans = 0
BA = 0
BX = 0
XA = 0
for s in S:
    ans += s.count("AB")
    if s[0]=="B" and s[-1]=="A":BA+=1
    elif s[0]=="B":BX+=1
    elif s[-1]=="A":XA+=1
ans += min(BX,XA) + max(0,BA - (BX==XA==0))
print(ans)

Solution (Python):
a = int(input())
ba = 0
count = 0
A = 0
B = 0
for i in range(a):
    l = input()
    count += l.count("AB")
    if l[0] == "B" and l[-1] == "A":
        ba += 1
    elif l[0] == "B":
        B += 1
    elif l[-1] == "A":
        A += 1
if ba == 0:
    count += min(A,B)
else:
    if A + B == 0:
        count += ba - 1
    else:
        count += ba + min(A,B)
print(count)

Solution (Python):
def solve(n, s):
    num = 0
    a, b, ab = 0, 0, 0
    for i in range(n):
        num += s[i].count("AB")
        if s[i].endswith("A"):
            a += 1
        if s[i].startswith("B"):
            b += 1
        if s[i].endswith("A") and s[i].startswith("B"):
            ab += 1
    a -= ab
    b -= ab
    cnt = 0
    if ab > 0:
        cnt += ab - 1
        if a > 0:
            cnt += 1
            a -= 1
        if b > 0:
            cnt += 1
            b -= 1
    cnt += min(a, b)
    return num + cnt

n = int(input())
s = [input() for i in range(n)]
print(solve(n, s))

Solution (Python):
N = int(input())
S = [input() for _ in range(N)]
first_B, last_A, both = 0, 0, 0
ans = 0
for s in S:
    ans += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A': both += 1
    elif s[0] == 'B': first_B += 1
    elif s[-1] == 'A': last_A += 1
if both <= 1:
    if last_A <= first_B: last_A += both
    else: first_B += both
    ans += max(min(first_B, last_A), 0)
else:
    ans += max(both-1, 0) + (1 if first_B else 0) + (1 if last_A else 0) + max(min(first_B-1, last_A-1), 0)
print(ans)

Solution (Python):

"""
.....A
B.....
を連結させればABは一個増える

(例)
...A
B...
B..A
が一個ずつある時、

...A B..A B...
とやる2が正解で、

...A B... B..A
とやると1で不正解

"""
def solve():
    N = int(input())

    ans = 0
    b_start = 0
    a_end = 0
    ryouhou = 0
    for i in range(N):
        s = input()
        ans += s.count("AB")
        
        if s[0] == "B" and s[-1] == "A":
            ryouhou += 1
        elif s[0] == "B":
            b_start += 1
        elif s[-1] == "A":
            a_end += 1
    
    
    if ryouhou > 0:
        ans += ryouhou - 1

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

    print(ans)
   
        

if __name__ == "__main__":
    solve()

Solution (Python):
n = int(input())
XA ,BA ,BX = 0 ,0 ,0
AB = 0
for i in range(n):
    s = str(input())
    AB += s.count("AB")
    if s[0] == "B":
        if s[-1] == "A":
            BA += 1
        else:
            BX += 1
    else:
        if s[-1] == "A":
            XA += 1

if BA > 1:
    AB += (BA-1)
    BA = 1
if XA:
    if BA:
        AB += 1
        XA -= 1
if BX:
    if BA:
        AB += 1
        BX -= 1
AB += min(XA,BX)
print(AB)

Solution (Python):
n = int(input())
XA ,BA ,BX = 0 ,0 ,0
AB = 0
for i in range(n):
    s = str(input())
    AB += s.count("AB")
    if s[0] == "B":
        if s[-1] == "A":
            BA += 1
        else:
            BX += 1
    else:
        if s[-1] == "A":
            XA += 1

if BA > 1:
    AB += (BA-1)
    BA = 1
if XA:
    if BA:
        AB += 1
        XA -= 1
if BX:
    if BA:
        AB += 1
        BX -= 1
AB += min(XA,BX)
print(AB)

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":
        if S[-1] == "A":
            AB += 1
        else:
            B += 1
    elif S[-1] == "A":
        A += 1

if AB:
    ans += AB-1
    if A:
        ans += 1
        A -= 1
    if B:
        ans += 1
        B -= 1

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" and S[-1]=="A":
        AB+=1
    elif S[0]=="B":
        B+=1
    elif S[-1]=="A":
        A+=1
C=min(A,B)
if A==0 and B==0:
    print(ans+max(0,AB-1))
elif C==0:
    print(ans+AB)
else:
    print(ans+AB+min(A,B))

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

count = 0
count_a = 0
count_b = 0
count_ab = 0
for i in range(n):
    if s[i][0] =='B' and s[i][-1] =='A':
        count_ab = count_ab + 1
    elif s[i][0] =='B':
        count_b = count_b + 1
    elif s[i][-1] =='A':
        count_a = count_a + 1
    
    count = count + s[i].count('AB')

if count_ab!=0 and count_b==0 and count_a ==0:
    count = count + count_ab-1
elif count_b==0 and count_a ==0:
    count = count
else:
    count = count +min(count_a,count_b) + count_ab

print(count)

Solution (Python):
N = int(input())
count = 0
end = 0
start = 0
double = 0
for i in range(N):
    line = input()
    if "AB" in line:
        count += line.count("AB")
    if line[0] == "B":
        if line[-1] == "A":
            double +=1
        else:
            start += 1
    elif line[-1] == "A":
            end += 1
if double == 0:
    count += min(start, end)
elif start + end > 0:
    count += double + min(start, end)
elif start + end == 0:
    count += double - 1
print(count)

Solution (Python):
import math
import fractions
import copy
import numpy as np

def j(q):
    if q==1: print("POSSIBLE")
    elif q == 0:print("IMPOSSIBLE")
    exit(0)
rem = pow(10,9)+7
"""
def ct(x,y):
    if (x>y):print("+")
    elif (x<y): print("-")
    else: print("?")
"""

def ip():
    return int(input())
def printrow(a):
    for i in a:
        print(i)
def combinations(n,r):
    if n<r:return 0
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
def permutations(n,r):
    if n<r:return 0
    return math.factorial(n) // math.factorial(n - r)
def lcm(x, y):
    return (x * y) // fractions.gcd(x, y)


n = ip()                                     






a=[input() for i in range(n)]    




type = [0 for i in range(4)]
s = 0
for i in a:
    s+=i.count("AB")
    if i[0] == 'B' and i[-1] == 'A': type[0]+=1    
    elif i[0] == 'B' and i[-1] != 'A': type[1]+=1  
    elif i[0] != 'B' and i[-1] == 'A': type[2]+=1  
    elif i[0] != 'B' and i[-1] != 'A': type[3]+=1  
if type[0] == 0:
    s+=min(type[1],type[2])
else:
    if type[1] or type[2]:
        s+=type[0]+ min(type[1],type[2])
    else:
        s+=type[0]-1
print(s)

Solution (Python):



import math
N = int(input())
l = []
for i in range(N):
   l.append(input())

default = sum([i.count('AB') for i in l])


a = sum([i[-1]=='A' and i[0]!='B' for i in l])

b = sum([i[0]=='B' and i[-1]!='A' for i in l])

ab = sum([i[0]=='B' and i[-1]=='A' for i in l])

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

print(num + default)

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

innerAB_cnt = 0
endA_cnt = 0
startB_cnt = 0
B_A_cnt = 0
for i in range(N):
    S = input()
    innerAB_cnt += S.count('AB')
    is_end_A = S[-1] == 'A'
    is_start_B = S[0] == 'B'
    if is_end_A and is_start_B:
        B_A_cnt += 1
    elif is_end_A:
        endA_cnt += 1
    elif is_start_B:
        startB_cnt += 1
remainder = abs(startB_cnt - endA_cnt)
if B_A_cnt == 0:
    print(min(endA_cnt, startB_cnt) + innerAB_cnt)
elif endA_cnt + startB_cnt > 0:
    print(min(endA_cnt, startB_cnt) + B_A_cnt + innerAB_cnt)
else:
    print(B_A_cnt-1 + innerAB_cnt)

Solution (Python):

import sys


def solve(N: int, S: "List[str]"):
    cnt = 0
    
    cnt_ba = 0
    cnt__a = 0
    cnt_b_ = 0

    for s in S:
        cnt += 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 cnt_ba > 0:
        cnt += cnt_ba - 1
        if cnt__a > 0:
            cnt += 1
            cnt__a -= 1

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

    cnt += min(cnt__a,cnt_b_)


    print(cnt)



    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):

from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LS()
    return l
sys.setrecursionlimit(1000000)
mod = 1000000007


def A():
    n,k = LI()
    print(n-k+1)
    return


def B():
    r,g,b,n = LI()
    ans = 0
    for i in range(n+1):
        x = r*i
        for j in range(n+1-x):
            y = g*j
            z = n-x-y
            if z%b != 0 or z < 0:continue
            ans += 1
    print(ans)
    return


def C():
    n = I()
    s = SR(n)
    f = [0 for i in range(n)]
    a = deque()
    b = deque()
    ba = deque()
    c = deque()
    l = 0
    for i in range(n):
        l += len(s[i])
        if s[i][-1] == "A":
            f[i] += 1
        if s[i][0] == "B":
            f[i] += 2
        if f[i] == 0:
            c.append(s[i])
        elif f[i] == 1:
            a.append(s[i])
        elif f[i] == 2:
            b.append(s[i])
        else:
            ba.append(s[i])
    ans = [None for i in range(l)]
    i = 0
    while a or b or c or ba:
        if a:
            x = a.popleft()
            for j in x:
                ans[i] = j
                i += 1
            while ba:
                x = ba.popleft()
                for j in x:
                    ans[i] = j
                    i += 1
            if b:
                x = b.popleft()
                for j in x:
                    ans[i] = j
                    i += 1
        elif b:
            x = b.popleft()
            for j in x:
                ans[i] = j
                i += 1
        elif c:
            x = c.popleft()
            for j in x:
                ans[i] = j
                i += 1
        while ba:
            x = ba.popleft()
            for j in x:
                ans[i] = j
                i += 1
    s = 0
    for i in range(l-1):
        if ans[i] == "A" and ans[i+1] == "B":
            s += 1
    print(s)
    return


def D():
    n = I()

    return


def E():
    n = I()

    return


def F():
    n = I()

    return


def G():
    n = I()

    return


def H():
    n = I()

    return


def I_():
    n = I()

    return


def J():
    n = I()

    return


if __name__ == "__main__":
    C()

Solution (Python):
import numpy as np

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


ABarray = np.zeros((N, 2), dtype=int)
count = 0
for i, alp in enumerate(s):
    ABarray[i, 0] = 1 if (alp[-1] == 'A') else 0
    ABarray[i, 1] = 1 if (alp[0] == 'B') else 0
    count += alp.count('AB')

both = np.count_nonzero(np.all(ABarray == 1, axis=1))
ABsum = np.sum(ABarray, axis=0)
Aonly = ABsum[0] - both
Bonly = ABsum[1] - both

if Aonly == 0 and Bonly == 0 and both >= 1:
    count += both - 1
else:
    count += min(Aonly, Bonly) + both
print(count)

Solution (Python):
import numpy as np

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


ABarray = np.zeros((N, 3), dtype=int)
count = 0
for i, alp in enumerate(s):
    ABarray[i, 0] = 1 if (alp[-1] == 'A') else 0
    ABarray[i, 1] = 1 if (alp[0] == 'B') else 0
    ABarray[i, 2] = 1 if (alp[0] == 'B' and alp[-1] == 'A') else 0
    count += alp.count('AB')

ABsum = np.sum(ABarray, axis=0)
both = ABsum[2]
Aonly = ABsum[0] - both
Bonly = ABsum[1] - both

if Aonly == 0 and Bonly == 0 and both >= 1:
    count += both - 1
else:
    count += min(Aonly, Bonly) + both
print(count)

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

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

c = 0
sb = ea = both = 0
for i in range(N):
    s = input()
    c += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        both += 1
    elif s[0] == 'B':
        sb += 1
    elif s[-1] == 'A':
        ea += 1

if both > 0:
    c += both-1
    if sb > 0:
        c += 1
        sb -= 1
    if ea > 0:
        c += 1
        ea -= 1
    c += min(sb, ea)
else:
    c += min(sb, ea)

print(c)

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

Solution (Python):


N=int(input())
cnt=0
ba=0
a=0
b=0

for i in range(N):
    chr=input()
    cnt+=chr.count('AB')
    if chr[0]=='B' and chr[-1]=='A':
        ba+=1
    elif chr[-1]=='A':
        a+=1
    elif chr[0]=='B':
        b+=1

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

Solution (Python):
N = int(input())
cnt = 0
end_A = 0
start_B = 0
start_B_AND_end_B = 0
for _ in range(N):
    s = input()
    if s.startswith('B') and s.endswith('A'):
        start_B_AND_end_B += 1
    elif s.startswith('B'):
        start_B += 1
    elif s.endswith('A'):
        end_A += 1
    
    cnt += s.count('AB')
    
    
if start_B_AND_end_B >= 1:
    cnt += start_B_AND_end_B - 1
    if end_A >= 1:
        cnt += 1
        end_A -= 1
    if start_B >= 1:
        cnt += 1
        start_B -= 1

cnt += min(end_A, start_B)

print(cnt)

Solution (Python):
n=int(input())
counta=0
countb=0
countspec=0
re=0
for i in range(n):
    s=input()
    re+=s.count("AB")
    if (s[0]=='B') and s[len(s)-1]=='A':
        countspec+=1
    else:
        if s[0]=='B':
            countb+=1
        else:
            if (s[len(s)-1]=='A'):
                counta+=1
if countspec>=1:
    re+=countspec-1
if countspec>=1:
    if counta>=1:
        counta-=1
        re+=1
    if countb>=1:
        countb-=1
        re+=1
re+=min(counta,countb)
print(re)

Solution (Python):
N = int(input())
S = []
for i in range(N):
    s = str(input())
    S.append(s)
    
count_AB = 0
for s in S:
    count_AB += s.count("AB")


count_BA = 0
count_A = 0
count_B = 0
for s in S:
    if s[0] == 'B' and s[-1] == 'A':
        count_BA += 1
    if s[0] != 'B' and s[-1] == 'A':
        count_A += 1
    if s[0] == 'B' and s[-1] != 'A':
        count_B += 1


if count_BA >= 1:
    count_AB += count_BA -1
if count_BA >= 1:
    if count_A >= 1:
        count_A -= 1
        count_AB += 1
    if count_B >= 1:
        count_B -= 1
        count_AB += 1
count_AB += min(count_A, count_B)
print(count_AB)

Solution (Python):
n = int(input())
ss = [input() for _ in range(n)]
ans = 0
count_ab = 0 
count_a = 0 
count_b = 0 
count_ba = 0 
for s in ss:
  slen = len(s)
  if s[0] == 'B' and  s[-1] == 'A':
    count_ba +=1
  else:
      if s[0] == 'B':
        count_b +=1
      if s[-1] == 'A':
        count_a +=1
  count_ab += s.count("AB")
 
if count_ba == 0:
    print(count_ab + min(count_a, count_b))
elif count_a == 0 and count_b == 0:
    print(count_ab + count_ba - 1)
elif count_a > 0 and count_b > 0:
    print(count_ab +  min(count_a, count_b) + count_ba)
else:
    print(count_ab + count_ba)

Solution (Python):
n = int(input())
a = 0
b = 0
ab = 0
total = 0
t = []

for i in range(n):
	t.append(input())

for i in t:
	total += i.count("AB")
	if i[-1] == "A" and i[0] == "B":
		ab += 1
	else:
		a += i[-1] == "A"
		b += i[0] == "B"
if ab == 0:
	print(total + min(a,b))
elif a == 0 and b == 0:
	print(total + ab - 1)
elif a > 0 and b > 0:
	print(total + ab + min(a, b))
else:
	print(total + ab)

Solution (Python):
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
from functools import lru_cache
import sys
sys.setrecursionlimit(10000)
INF = float("inf")
YES, Yes, yes, NO, No, no = "YES", "Yes", "yes", "NO", "No", "no"
dy4, dx4 = [0, 1, 0, -1], [1, 0, -1, 0]
dy8, dx8 = [0, -1, 0, 1, 1, -1, -1, 1], [1, 0, -1, 0, 1, 1, -1, -1]


def inside(y, x, H, W):
    return 0 <= y < H and 0 <= x < W


def ceil(a, b):
    return (a + b - 1) // b



def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)


def lcm(a, b):
    g = gcd(a, b)
    return a / g * b


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

    ans = 0
    a, b, ba = 0, 0, 0
    for _ in range(N):
        S = input()
        ans += S.count("AB")

        if S[0] == "B" and S[-1] == "A":
            ba += 1
        elif S[-1] == "A":
            a += 1
        elif S[0] == "B":
            b += 1

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

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

    
    ans += min(a, b)

    print(ans)


if __name__ == '__main__':
    main()

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

Solution (Python):
import sys,random
try: sys.stdin = open('in.in','r')
except: pass

ans = 0
allboth = 1
l = r = 0

n = int(input())
for i in range(n):
	s = input().strip()
	ans += s.count('AB')
	if s[0] == 'B' or s[-1] == 'A':
		l += s[0] == 'B'
		r += s[-1] == 'A'
		if s[0] != 'B' or s[-1] != 'A':
			allboth = 0

ans += min(l,r)
if allboth and l:
	ans -= 1
print(ans)

Solution (Python):
n = int(input())
s_list = [input() for x in range(n)]

cnt = 0
a_cnt = 0
b_cnt = 0
ab_cnt = 0
for x in s_list:
    cnt += x.count("AB")
    if (x[-1] == "A")&(x[0] != "B"):
        a_cnt += 1
    if (x[0] == "B")&(x[-1] != "A"):
        b_cnt += 1
    if (x[-1] == "A")&(x[0] == "B"):
        ab_cnt += 1
if ab_cnt == 0:
    print(cnt+min(a_cnt,b_cnt))
elif (a_cnt+b_cnt>0)&(ab_cnt != 0):
    print(cnt+ab_cnt+min(a_cnt,b_cnt))
elif (a_cnt+b_cnt==0):
    print(cnt+ab_cnt-1)

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

cnta = 0
cntb = 0
isok = False
cnt = 0


for i in range(n):
    if s[i][0] == 'B' and s[i][-1] =='A':
        cnta+=1
        cntb+=1
    elif s[i][0] =='B':
        cntb+=1
        isok = True
    elif s[i][-1] =='A':
        cnta+=1
        isok=True
    for j in range(len(s[i])-1):
        if s[i][j] =='A' and s[i][j+1] == 'B':
            cnt += 1


if isok:
    print(min(cnta,cntb)+cnt)
else:
    print(max(cnta-1,0)+cnt)

Solution (Python):
N=int(input())
st=[0]*N
for i in range(N):
    st[i]=input()
ans=0
c1=0 
c2=0
c3=0
for i in st:
    ans+=i.count("AB")
    if i[0]=="B" and i[-1]=="A":
        c1+=1
    elif i[0]=="B":
        c2+=1
    elif i[-1]=="A":
        c3+=1
if c1==0:
    ans+=min(c2,c3)
elif c2+c3>0:
    ans=ans+c1+min(c2,c3)
else:
    ans=ans+c1-1
print(ans)

Solution (Python):

import itertools

N = int(input())
li = []
lasta = 0
firstb = 0
ab = 0
cnt = 0



for i in range(N):
    s = input()
    cnt += s.count('AB')
    li = list(s)
    if li[-1] == 'A' and li[0] != 'B':
        lasta += 1
    if li[0] == 'B' and li[-1] != 'A':
        firstb += 1
    if li[-1] == 'A' and li[0] == 'B':
        ab += 1



if ab == 0:
    cnt += min(lasta,firstb)
elif ab != 0 and lasta + firstb > 0:
    cnt += ab + min(lasta, firstb)
elif ab != 0 and lasta + firstb == 0:
    cnt += ab - 1

print(cnt)

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

ans = 0

leftB = rightA = leftB_and_rightA = 0

for l in L :
    ans += l.count("AB")
    if (l[0] != "B") and (l[-1] != "A") :
        continue
    elif (l[0] == "B") and (l[-1] != "A") :
        leftB += 1
    elif (l[0] != "B") and (l[-1] == "A") :
        rightA += 1
    else :
        leftB_and_rightA += 1

if leftB_and_rightA :
    ans += (leftB_and_rightA - 1)
    
    if leftB :
        ans += 1
        leftB -= 1
    
    if rightA :
        ans += 1
        rightA -= 1

ans += min(leftB, rightA)

print(ans)

Solution (Python):
N = int(input())
S = [input() for i in range(N)]
cnt_ab_from_S = sum([s.count('AB') for s in S])
start_from_b_and_end_at_a = sum([(s[0] == 'B') and (s[-1] == 'A') for s in S])
not_start_from_b_and_end_at_a = sum([(s[0] != 'B') and (s[-1] == 'A') for s in S])
start_from_b_and_not_end_at_a = sum([(s[0] == 'B') and (s[-1] != 'A') for s in S])
ans = cnt_ab_from_S
if (start_from_b_and_end_at_a == 0):
    ans += min(not_start_from_b_and_end_at_a, start_from_b_and_not_end_at_a)
elif (not_start_from_b_and_end_at_a + start_from_b_and_not_end_at_a == 0):
    ans += (start_from_b_and_end_at_a - 1)
else:
    ans += (start_from_b_and_end_at_a + min(not_start_from_b_and_end_at_a, start_from_b_and_not_end_at_a))
print(ans)

Solution (Python):

"""
C - AB Substrings
https://atcoder.jp/contests/diverta2019/tasks/diverta2019_c

"""
import sys


def solve(N, words):
    eA, sB, both = 0, 0, 0
    ans = 0
    for w in words:
        ans += w.count('AB')
        if w[-1] == 'A':
            if w[0] == 'B':
                both += 1
            else:
                eA += 1
        elif w[0] == 'B':
            sB += 1

    if both == 0:
        ans += min(eA, sB)
    elif eA == 0 and sB == 0:
        ans += (both - 1)
    else:
        ans += min(eA, sB) + both
    return ans


def main(args):
    N = int(input())
    words = [input() for _ in range(N)]
    ans = solve(N, words)
    print(ans)


if __name__ == '__main__':
    main(sys.argv[1:])

Solution (Python):
import re
N = int(input())
S = []
a, b, ab,c = 0, 0, 0, 0
for i in range(N):
	S.append(input())
	c += len(re.findall("AB", S[i]))
	if S[i][-1] == "A" and S[i][0] == "B":
		ab += 1
	if S[i][-1] == "A":
		a += 1
	if S[i][0] == "B":
		b += 1
if ab == a == b:
	seq = max(ab -1, 0)
else:
	seq = min (a,b)

print(seq + c)

Solution (Python):
N = int(input())
ans = 0
c1 = 0
c2 = 0
c3 = 0
ans = 0
for _ in range(N):
    s = input()
    ans += s.count("AB")
    if (s[0]=="B") & (s[-1]=="A"):
        c1 += 1
    elif s[0] == "B":
        c2 += 1
    elif s[-1]=="A":
        c3 += 1

if c1== 0:
    print(ans + min(c2, c3))
elif (c1 > 0) & (max(c2, c3) == 0):
    print(ans + c1 - 1)
elif (c1 > 0) & (max(c2, c3) > 0):
    print(ans + c1 + min(c2, c3))

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

counter = 0

b_and_a = 0
first_b = 0
last_a = 0
for _ in range(n):
    w = input()
    counter += w.count("AB")

    if w[0] == "B" and w[-1] == "A":
        b_and_a += 1
    elif w[0] == "B":
        first_b += 1
    elif w[-1] == "A":
        last_a += 1
    else:
        pass

if b_and_a == 0:
    counter += min(first_b, last_a)
else:
    if b_and_a >= 2:
        counter += (b_and_a - 1)

    if first_b >= 1:
        counter += 1
        first_b -= 1
    if last_a >= 1:
        counter += 1
        last_a -= 1

    counter += min(first_b, last_a)

print(counter)

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

countXA = 0
countBX = 0
countBXA = 0
countAB = 0

for i in range(N):
  line = input()
  if line[0] == 'B' and line[-1] == 'A':
    countBXA += 1
  elif line[0] == 'B':
    countBX += 1
  elif line[-1] == 'A':
    countXA += 1
  countAB += line.count('AB')

if countBXA > 0 and countBX == 0 and countXA == 0:
  countAB += countBXA - 1
else:
  countAB += min(countBX, countXA) + countBXA

print(countAB)

Solution (Python):
import re

class Solver:
    def __init__(self, num):
        self.n = num
        self.ans = 0

        
        self.case_0 = 0

        
        self.case_1 = 0

        
        self.case_2 = 0

        
        self.case_3 = 0

        
        
        

        self.solve()
    
    def solve(self):
        for i in range(self.n):
            sen = input()
            if sen.find("AB") != -1:
                for m in re.finditer(r"AB", sen):
                    self.case_0 = self.case_0 + 1
            if sen[0] == "B" and sen[-1] == "A":
                self.case_1 = self.case_1 + 1
            elif sen[0] == "B" and sen[-1] != "A":
                self.case_2 = self.case_2 + 1
            elif sen[0] != "B" and sen[-1] == "A":
                self.case_3 = self.case_3 + 1
    

        if self.case_1 == 0:
            self.ans = self.ans + min(self.case_3, self.case_2)
        else:
            if self.case_3 + self.case_2 > 0:
                self.ans = self.ans + self.case_1 + min(self.case_3, self.case_2)
            elif self.case_3 + self.case_2 == 0:
                self.ans = self.ans + self.case_1 - 1

        self.ans = self.ans + self.case_0

        print(str(self.ans))

def main():
    n=int(input())
    Solver(n)



if __name__ == "__main__":
    main()

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

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

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

Solution (Python):
read = input
n = int(read())
ans = 0
B = 0
A = 0
BA = 0
for i in range(n):
    s = read()
    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 += min(A,B)
else  :
    if A + B == 0:
        ans += BA - 1
    else :
        ans += BA + min(A,B)
print(ans)