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):
target = "AB"
N = int(input())
ans = 0
finish_A = set()
start_B = set()
for i in range(N):
    s = input()
    lens = len(s)
    index = 0
    if s[-1] == "A":
        finish_A.add(i)
    if s[0] == "B":
        start_B.add(i)
    while index <= lens-2:
        if s[index:index+2] == target:
            ans += 1
            index += 2
            continue
        index += 1
both = len(finish_A & start_B)
onlyA = len(finish_A) - both
onlyB = len(start_B) - both
if onlyA < onlyB:
    print(str(ans + onlyA + both))
elif onlyB < onlyA:
    print(str(ans + onlyB + both))
elif both == 0:
    print(str(ans + onlyA))
elif onlyA > 0:
    print(str(ans + onlyA + both))
else:
    print(str(ans + onlyA + both - 1))

Solution (Python):
import numpy as np

n=int(input())
a=0
b=0
ab=0
count=0
for i in range(n):
    s=input()
    if s[0]=='B':
        a+=1
    if s[-1]=='A':
        b+=1
    if s[0]=='B' and s[-1]=='A':
        ab+=1
    for j in range(len(s)-1):
        if s[j]=='A' and s[j+1]=='B':
            count+=1
if a>0 and a==ab and b==ab:
    count+=min([a,b])-1
else:
    count+=min([a,b])
print(count)

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

N = int(input())
S = [input() for _ in range(N)]
l, m, n = 0, 0, 0
ans = 0
for s in S:
    if s[0] == 'B' and s[-2] == 'A':
        n += 1
    elif s[0] == 'B':
        m += 1
    elif s[-2] == 'A':
        l += 1
    for i in range(len(s)-1):
        if s[i:i+2] == 'AB':
            ans += 1
if n > 0:
    ans += n - 1
    if l > 0:
        l -= 1
        ans += 1
    if m > 0:
        m -= 1
        ans += 1
ans += min(l, m)
print(ans)

Solution (Python):
l = raw_input().split()
N = int(l[0])
S = [0]*N
for i in range(N):
    l = raw_input().split()
    S[i] = l[0]



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


numA = 0
numB = 0
numAB = 0
for s in S:
    if s[0] != 'B' and s[-1] == 'A':
        numA += 1
    if s[0] == 'B' and s[-1] != 'A':
        numB += 1
    if s[0] == 'B' and s[-1] == 'A':
        numAB += 1

count += min(numA, numB)
if numAB > 0:
    count += numAB - 1
if (numA > 0 or numB > 0) and numAB > 0:
    count += 1
print(count)

Solution (Python):
import sys
import 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()
s = [input() for _ in range(n)]

lis1 = []
lis2 = []
lis3 = []
lis4 = []

for x in s:
    if (x[0] == 'B' and x[-1] == 'A'):
        lis1.append(x)
        
    if (x[-1] == 'A' and x not in lis1):
        lis2.append(x)

    if (x[0] == 'B' and x not in lis1):
        lis3.append(x)
        
for x in s:
    if 'AB' in x and x not in lis1 and x not in lis2 and x not in lis3:
        lis4.append(x)






ct = 0
for x in lis1:
    ct += x.count('AB')
for x in lis2:
    ct += x.count('AB')
for x in lis3:
    ct += x.count('AB')
for x in lis4:
    ct += x.count('AB')


if lis2 == [] and lis3 != []:
    p = len(lis1)
    q=max(len(lis1)-p-1,0)

    

    print(ct + p)

elif lis2 == [] and lis3 == []:
    print(max(len(lis1) - 1,0) + ct)

else :        
    p = min(len(lis2), len(lis3))
    q = len(lis1)

    

    print(ct + p + q)

Solution (Python):
N = int(input())
s = [0] * N
for i in range(N):
	s[i] = input()
ans = 0
for j in range(N):
	ans += s[j].count("AB")
acnt, bcnt, bacnt = 0, 0, 0
for k in range(N):
	if s[k][0] == "B" and s[k][-1] == "A":
		bacnt += 1
	elif s[k][0] == "B":
		bcnt += 1
	elif s[k][-1] == "A":
		acnt += 1
if acnt >= 1 and bcnt >= 1:
	ans += (bacnt + 1) + max(0, min(acnt - 1, bcnt - 1))
elif acnt >= 1 or bcnt >= 1:
	ans += bacnt
else:
	ans += max(0, bacnt - 1)
print(ans)

Solution (Python):
n=int(input())
a=[input() for i in range(n)]
count=0
ca=0
cb=0
cc=0
for i in a:
    count+=i.count('AB')
    if i[0]=='B':cb+=1
    if i[-1]=='A':ca+=1
    if i[0]=='B' and i[-1]=='A':cc+=1
ans=count+min(ca,cb)
if max(ca,cb)==cc and cc!=0:ans-=1
if len(a)==1:ans=a[0].count('AB')
print(ans)

Solution (Python):
N=input()
LL=[]
def find(s):
    count=0
    for i in xrange(len(s)-1):
        if s[i]+s[i+1]=='AB':
            count+=1
    return count        
 
ans=0
start_B=0
end_A=0
same_time=0
for i in xrange(N):
    s=raw_input()
    ans+=find(s)
    if s[-1]=='A':
        end_A+=1
    if s[0]=='B':
        start_B+=1   
    if s[0]=='B' and s[-1]=='A':
        same_time+=1
 
 

final=ans+min(end_A-same_time,start_B-same_time)
if end_A!=start_B:
    print(final+same_time)
else:
    if end_A-same_time>0:
        print(final+max(same_time,0))
    else:
        print(final+max(same_time-1,0))

Solution (Python):
N=input()
LL=[]
def find(s):
    count=0
    for i in xrange(len(s)-1):
        if s[i]+s[i+1]=='AB':
            count+=1
    return count        
 
ans=0
start_B=0
end_A=0
same_time=0
for i in xrange(N):
    s=raw_input()
    ans+=find(s)
    if s[-1]=='A':
        end_A+=1
    if s[0]=='B':
        start_B+=1   
    if s[0]=='B' and s[-1]=='A':
        same_time+=1
 
 

final=ans+min(end_A-same_time,start_B-same_time)
if end_A!=start_B:
    print(final+same_time)
else:
    if end_A-same_time>0:
        print(final+max(same_time,0))
    else:
        print(final+max(same_time-1,0))

Solution (Python):
n = int(input())
a = 0
b = 0
ab = 0
b_a = 0
for i in range(n):
    s = input()
    if s[0] == "B" and s[-1] == "A":
        b_a += 1
    elif s[0] == "B":
        b += 1
    elif s[-1] == "A":
        a += 1
    for j in range(len(s) - 1):
        if s[j] == "A" and s[j + 1] == "B":
            ab += 1
if a > b:
    a, b = b, a
ans = ab
if b == 0:
    if b_a != 0:
        ans += b_a - 1
elif a + b == 1:
    ans += b_a
else:
    ans += b_a + a
print(ans)

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

ab_cnt = 0
a_saigo = 0
b_atama = 0
ba_cnt = 0
for s in s_list:
    ab_cnt += s.count("AB")
    if s[0] =="B":
        b_atama += 1
    if s[-1] == "A":
        a_saigo += 1
    if s[0] =="B" and s[-1] == "A":
        ba_cnt += 1

result = ab_cnt + min(b_atama,a_saigo)
if b_atama == ba_cnt and a_saigo == ba_cnt and ba_cnt != 0:
    result += -1

print(result)

Solution (Python):



N = int(input())

count_AB = 0
count_last_A = 0
count_first_B = 0
count_both = 0
for i in range(N):
    s = input().rstrip()
    
    count_AB += len(s.split('AB')) - 1
    
    if s[0] == 'B' and s[-1] == 'A':
        count_both += 1
    elif s[0] == 'B':
        count_first_B += 1
    elif s[-1] == 'A' :
        count_last_A += 1
        
max_AB = max(count_last_A, count_first_B)
min_AB = max(count_last_A, count_first_B)

temp = 0
if count_both > 0:
    temp += count_both - 1
    count_both = 1
    
    if max_AB > 0:
        temp += 1
        count_both = 0
        max_AB -= 1
        min_AB += 1
        
if count_both == 0:
    temp += min(count_last_A, count_first_B)
    
print(count_AB + temp)

Solution (Python):
n=int(input())
a=0;b=0;c=0
ans=0
for i in range(n):
  s=list(input())
  if s[0]=='B':
    if s[-1]=='A':
      a+=1
    else:
      b+=1
  elif s[-1]=='A':
    c+=1
  for j in range(len(s)-1):
    if s[j]=='A' and s[j+1]=='B':
      ans+=1
if a>0:
  if b>0 and c>0:
    mn=min(b-1,c-1)
    ans+=a+1+mn
  elif b>0 and c==0:
    ans+=a
  elif c>0 and b==0:
    ans+=a
  else:
    ans+=a-1
else:
  ans+=min(b,c)
print(ans)

Solution (Python):
N=int(input())
M=['',[],[],'']

for i in range(N):
    m=str(input())
    if m[0]!='B' and m[-1:]!='A':
        M[0]+=m
    elif m[0]!='B' and m[-1:]=='A':
        M[1].append(m)
    elif m[0]=='B' and m[-1:]!='A':
        M[2].append(m)
    else:
        M[3]+=m

if not M[1] and not M[2]:
    M[0]+=M[3]
elif not not M[1] and not M[2]:
    M[0]+=''.join(M[1])+M[3]
elif not M[1] and not not M[2]:
    M[0]+=M[3]+''.join(M[2])
else:
    M[0]+=M[1][0]+M[3]+M[2][0]
    M[1].pop(0)
    M[2].pop(0)
    for i in range(min(len(M[1]),len(M[2]))):
        M[0]+=M[1][i]+M[2][i]
    del M[1][0:i+1]
    del M[2][0:i+1]
    M[0]+=''.join(M[1])+''.join(M[2])
print(M[0].count('AB'))

Solution (Python):
N = int(input())
l=[]
cnt=a_cnt=b_cnt=ab_cnt=0
for n in range(N):
	s = input()
	if s[0] == 'B':
		b_cnt += 1
	if s[-1] == 'A':
		a_cnt += 1
	if s[0] == 'B' and s[-1] == 'A':
		ab_cnt += 1
	for i in range(len(s)-1):
		if s[i:i+2] == 'AB':
			cnt += 1
	l.append(s)

if ab_cnt == a_cnt and ab_cnt == b_cnt:
	if ab_cnt == 0:
		print(cnt)
	else:
		print(ab_cnt-1+cnt)
else:
	m = min(a_cnt,b_cnt)
	print(m+cnt)

Solution (Python):
N = int(input())
l=[]
cnt=a_cnt=b_cnt=ab_cnt=0
for n in range(N):
	s = input()
	if s[0] == 'B':
		b_cnt += 1
	if s[-1] == 'A':
		a_cnt += 1
	if s[0] == 'B' and s[-1] == 'A':
		ab_cnt += 1
	for i in range(len(s)-1):
		if s[i:i+2] == 'AB':
			cnt += 1
	l.append(s)

if ab_cnt == a_cnt and ab_cnt == b_cnt:
	if ab_cnt == 0:
		print(cnt)
	else:
		print(ab_cnt-1+cnt)
else:
	m = min(a_cnt,b_cnt)
	print(m+cnt)

Solution (Python):

n = int(input())
s = list()
counter = {
    'ab': 0,
    'begin_b': 0,
    'end_a': 0,
    'b_to_a': 0
}

for i in range(n):
    substr = input()
    counter['ab'] += substr.count('AB')
    if substr.startswith('B'):
        if substr.endswith('A'):
            counter['b_to_a'] += 1
        else:
            counter['begin_b'] += 1
    else:
        if substr.endswith('A'):
            counter['end_a'] += 1

total = counter['ab'] + min(counter['begin_b'], counter['end_a'])
if counter['b_to_a'] > 0:
    total += (counter['b_to_a'] - 1)
    if max(counter['begin_b'], counter['end_a']) > 0:
        total += 1

print(total)

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

a = b = ab = ba = 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')

p = min([ba, a, b])
ab += 2*p
ba -= p
a -= p
b -= p

if ba == 0:
    ab += min([a, b])
else:
    ab += ba
    if p == 0 and a == 0 and b == 0:
        ab -= 1

print(ab)

Solution (Python):
N=int(input())
list=[]
for x in range(N):
    list.append(input())
count=0
acount=0
bcount=0
abcount=0
for c in range(N):
    count=count+list[c].count('AB')
    if list[c][0]=='B':
        bcount=bcount+1
        if list[c][-1]=='A':
            abcount=abcount+1
    if list[c][-1]=='A':
        acount=acount+1
xx=min(acount,bcount)
if abcount==acount==bcount:
    if abcount==0:
        print(count+xx)
    else:
        print(count+xx-1)
else:
    print(count+xx)

Solution (Python):
n = int(input())
cnt = 0
ca = 0
cb = 0
cab = 0

for i in range(n):
    s = input()
    cnt += s.count('AB')
    if s[-1] == 'A':
        ca += 1
    if s[0] == 'B':        
        cb += 1
    if s[-1] == 'A' and s[0] == 'B':
        cab += 1

m1 = min(ca, cb)
m2 = max(ca, cb)
if m2 == cab and cab != 0:
    m1 -= 1
print(cnt+m1)

Solution (Python):
N = int(input())
s = [input() for i in range(N)]
count = 0
flag = 1
a_count = 0
b_count = 0
for i in range(N):
    count += s[i].count('AB')
    if s[i][0]=='B' and s[i][-1]!='A':
        flag = 0
    if s[i][0]!='B' and s[i][-1]=='A':
        flag = 0
    if s[i][0]=='B':
        b_count += 1
    if s[i][-1] =='A':
        a_count += 1

if a_count >0 and b_count > 0:
    count += min(a_count, b_count)-flag

print(count)

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

enda = 0
startb = 0
btoa = 0
ans = 0

for i in s:
    if i[0] == 'B' and i[-1] == 'A':
        btoa += 1
    elif i[-1] =='A':
        enda += 1
    elif i[0] == 'B':
        startb += 1
    ans += i.count('AB')



if btoa >= 1:
    ans += btoa - 1
    btoa = 1
    if enda > 0 and startb > 0:
        ans += 2
        btoa = 0
        enda -= 1
        startb -= 1
    elif enda > 0:
        ans += 1
        enda -= 1
    elif startb > 0:
        ans += 1
        startb -= 1

if enda < startb:
    enda, startb = startb, enda
ans += startb
enda -= startb
startb = 0

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

    a = b = c = m = 0

    for i in range(n):
        s = input()
        m += s.count('AB')

        if s[-1] == 'A' and s[0] == 'B':
            c += 1
        else:
            a += s[-1] == 'A'
            b += s[0] == 'B'

    if c and a:
        a -= 1
        m += 1

    if c and b:
        b -= 1
        m += 1

    m += max(0, c - 1) + min(a, b)

    print(m)




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())
K=[]
ans=0
ans2=0
AA=0
BB=0
BA=0
for i in range(N):
    s=input().strip()
    ans+=s.count('AB')
    ans2+=s.count('AB')
    if s[0]=='B' and s[-1]=='A':
        BA+=1
    elif s[0]=='B':
        BB+=1
    elif s[-1]=='A':
        AA+=1

tmp=min(AA,BB)
tmp2=max(AA-tmp, BB-tmp)
tmp3=min(BA,tmp2)
if tmp3==BA:
    tmp4=0
elif tmp3==tmp2 and tmp2!=0:
    tmp4=(BA-tmp3)
elif tmp3==tmp2 and tmp2==0:
    tmp4=(BA-tmp3)-1
ans=ans+tmp+tmp3+tmp4

ans2+=BA
if BA>0:
    ans2-=1
if BA>0:
    if BB>0:
        BB-=1
        ans2+=1
    if AA>0:
        AA-=1
        ans2+=1
kk=min(BB,AA)
if kk>0:
    ans2+=kk

print(max(ans,ans2))

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

ans = 0
num_a = 0
num_b = 0
num_ba = 0
num_ab = 0
for i in s:
    if(i[-1]=='A' and i[0]=='B'):
        num_ba += 1
    elif(i[-1]=='A'):
        num_a+=1
    elif(i[0]=='B'):
        num_b+=1
    last = ''
    for k in i:
        if(k=='A'):
            last = 'A'
        elif(last == 'A' and k=='B'):
            num_ab += 1
            last = ''
        else:
            last = ''

ans += num_ab

num_conn = min(num_a,num_b)
if(num_a!=num_b and num_ba!=0):
    ans+=num_ba+num_conn
elif(num_ba==0):
    ans+=num_conn
elif(num_a==0 and num_b==0):
    ans+=num_ba-1
else:
    ans+=num_ba+num_conn
print(ans)

Solution (Python):

import copy
import random
import bisect 
import fractions 
import math

mod = 10**9+7

N = int(input())
s = [0 for i in range(N)]
cnt = 0
chance = False
A_cnt = 0
B_cnt = 0
BA_cnt = 0
for i in range(N):
    s[i] = str(input())
    cnt += s[i].count("AB")
    if s[i][0] == "B" and s[i][-1]=="A":
        BA_cnt += 1
    elif s[i][0] == "B":
        B_cnt += 1
    elif s[i][-1] == "A":
        A_cnt += 1


if BA_cnt != 0 and A_cnt == 0 and B_cnt == 0:
    plus = BA_cnt - 1
elif BA_cnt != 0 and A_cnt == 0:
    plus = min(BA_cnt,BA_cnt+B_cnt)
elif BA_cnt != 0 and B_cnt == 0:
    plus = min(BA_cnt,BA_cnt+A_cnt)
else:
    plus = min(BA_cnt+A_cnt,BA_cnt+B_cnt)

cnt += plus

print(cnt)

Solution (Python):
import sys
def input():
    return sys.stdin.readline()[:-1]


N = int(input())

head_b_count = 0
tail_a_count = 0

head_b_tail_a_count = 0

total = 0

for _ in range(N):

    s = input()

    if s[0] == 'B':
        head_b_count += 1
    if s[-1] == 'A':
        tail_a_count += 1
    if s[0] == 'B' and s[-1] == 'A':
        head_b_tail_a_count += 1

    total += s.count('AB')

additional = min(head_b_count, tail_a_count)

if head_b_count == tail_a_count == head_b_tail_a_count != 0:
    additional -= 1

total += additional

print(total)

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

ans = 0
dic = {"A": 0, "B": 0}
dic2 = {"AB": 0, "A": 0, "B": 0}
for i in range(N):
    S = list(str(input()))
    pre = S[0]
    for j in range(1, len(S)):
        if (S[j - 1] + S[j]) == "AB":
            ans += 1
    if S[-1] == "A":
        dic["A"] += 1
    if S[0] == "B":
        dic["B"] += 1

    if S[-1] == "A" and S[0] == "B":
        dic2["AB"] += 1
    elif S[-1] == "A":
        dic2["A"] += 1
    elif S[0] == "B":
        dic2["B"] += 1

if dic2["A"] == 0 and dic2["B"] == 0:
    print(ans + max(dic2["AB"] - 1, 0))
else:
    print(ans + min(dic["A"], dic["B"]))

Solution (Python):
N = int(input())
numofAB = 0
numofLastA = 0
numofStartB = 0
numofLastAandStartB = 0
for _ in range(N):
    IN = input()
    numofAB += IN.count('AB')
    if IN[0] == 'B':
        numofStartB += 1
    if IN[-1] == 'A':
        numofLastA += 1
    if IN[0] == 'B' and IN[-1] == 'A':
        numofLastAandStartB += 1

numofLastA -= numofLastAandStartB
numofStartB -= numofLastAandStartB

if numofLastA > numofStartB:
    numofAB += numofStartB + numofLastAandStartB
else:
    numofAB += numofLastA + numofLastAandStartB
if numofLastA == 0 and numofStartB == 0 and numofLastAandStartB>0 :
    numofAB -= 1

print("{}".format(numofAB))

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

cnt = 0
head_b_cnt = 0
end_a_CNT = 0
head_a_end_b_cnt = 0
for word in s:
    cnt += word.count('AB')
    if word[0] == 'B':
        head_b_cnt += 1
    if word[-1] == 'A':
        end_a_CNT += 1
    if word[0] == 'B' and word[-1] == 'A':
        head_a_end_b_cnt += 1

if (head_b_cnt ==  end_a_CNT ==  head_a_end_b_cnt and head_a_end_b_cnt > 0):
    cnt += min(head_b_cnt, end_a_CNT) - 1
else:
    cnt += min(head_b_cnt, end_a_CNT)

print(cnt)

Solution (Python):
n = int(input())
B = 0
A = 0
AB = 0
count = 0

for _ in range(n):
    line = list(input())
    for i in range(len(line)-1):
        if line[i] == 'A' and line[i+1] == 'B':
            count += 1
    if line[0] == 'B' and line[len(line)-1] == 'A':
        AB += 1
    elif line[0] == 'B':
        B += 1
    elif line[len(line)-1] == 'A':
        A += 1


if AB > 1:
    count += AB - 1
    if A > 0:
        count += 1
    if B > 0:
        count += 1
    if A-1 > 0 and B-1 > 0:
        count += min([A-1,B-1])
elif AB == 1:
    if A > 0:
        count += 1
    if B > 0:
        count += 1
    if A-1 > 0 and B-1 > 0:
        count += min([A-1,B-1])
else:
    count += min([A,B])

print(count)

Solution (Python):


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

flag = False
count = 0
for i in range(len(s)):
    flag = False
    for j in range(len(s[i])):
        if flag == True and s[i][j] == 'B':
            count += 1
            flag = False
        elif s[i][j] == 'A':
            flag = True
        else:
            flag = False



startcnt = [0] * N
endcnt = [0] * N
for i in range(len(s)):
    if s[i][0] == 'B':
        startcnt[i] = 1
    if s[i][len(s[i])-1] == 'A':
        endcnt[i] = 1



cntpls = [0,0,0] 
for i in range(N):
    if startcnt[i] == 1 and  endcnt[i] == 0:
        cntpls[0]+= 1
    elif startcnt[i] == 0 and  endcnt[i] == 1:
            cntpls[1] += 1
    elif startcnt[i] == 1 and  endcnt[i] == 1:
        cntpls[2] += 1



add = 0
if cntpls[2] > 0:
    count += cntpls[2] - 1
    if cntpls[1] >= 1:
        add += 1
        cntpls[1] -= 1

    if cntpls[0] >= 1:
        add += 1
        cntpls[0] -= 1

print(count + add + min(cntpls[0],cntpls[1]))

Solution (Python):
N = int(input())
ss = 0
sl = 0
ssl = 0
cou = 0
for i in range(N):
    s = input()
    cou += s.count("AB")
    if s[0] == "B" and s[-1] != "A":
        ss += 1
    if s[-1] == "A" and s[0] != "B":
        sl += 1
    if s[0] == "B" and s[-1] == "A":
        ssl += 1
if ssl == 0 and ss == 0 and sl == 0:
    print(cou)
elif ssl != 0 and ss == 0 and sl == 0:
    print(cou + ssl -1)
elif ssl != 0 and ss != 0 and sl == 0:
    print(cou + ssl)
elif ssl != 0 and ss == 0 and sl != 0:
    print(cou + ssl)
else:
    print(cou + ssl + 1 + min(ss - 1, sl - 1))

Solution (Python):
n = int(input())
ans = 0
ab = 0
a = 0
b = 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

b,a = sorted([a,b])
if ab > 0:
    ans += ab-1
    ab = 1
if a > 0:
    ans += ab
ans += b
print(ans)

Solution (Python):


N = int(input())
s_list = [input() for i in range(N)]
cnt = sum([s.count("AB") for s in s_list])
a_end, b_start, a_b = 0, 0, 0

for s in s_list:
    if s[0] == "B" and s[-1] == "A":
        a_b += 1
    elif s[0] == "B":
        b_start += 1
    elif s[-1] == "A":
        a_end += 1
if a_b == 0:
    cnt += min(a_end, b_start)
else:
    cnt += a_b - 1
    if a_end >= 1:
        cnt += 1
        a_end -= 1
    if b_start >= 1:
        cnt += 1
        b_start -= 1
    cnt += min(a_end, b_start)
print(cnt)

Solution (Python):


n = int(input())

AB = 0
A = 0
B = 0
B_A = 0
for i in range(n):
    s = input()
    if s[0] == 'B' and s[-1] != 'A':
        B = B+1
    if s[0] != 'B' and s[-1] == 'A':
        A = A+1
    if s[0] == 'B' and s[-1] == 'A':
        B_A = B_A+1

    for j in range(len(s)-1):
        if s[j] == 'A' and s[j+1] == 'B':
            AB = AB + 1
ans = 0
if A>0:
    ans = B_A
    if B>0:
        ans = ans + 1
        if A-1>0 and B-1>0:
            ans = ans+min(A-1, B-1)

elif A == 0 and B_A>0:
    ans = B_A-1
    if B>0:
        ans = ans + 1
        if A-1>0 and B-1>0:
            ans = ans+min(A-1, B-1)

ans = ans + AB
print(ans)

Solution (Python):
import re


pattern = "AB"
num_input = int(input())

total_ab = 0

num_ab = 0
num_end_with_a = 0
num_start_with_b = 0
num_both = 0

prints = []

for i in range(0, num_input):
    input_string = input()
    num_ab += len(re.findall(pattern, input_string))
    start_with_b = (input_string[0] == 'B')
    end_with_a = (input_string[-1] == 'A')

    if start_with_b and end_with_a:
        num_both += 1
    elif start_with_b:
        num_start_with_b += 1
    elif end_with_a:
        num_end_with_a += 1




total_ab += num_ab




if num_end_with_a == 0 and num_start_with_b == 0:
    if num_both >= 2:
        num_both -= 2
        num_end_with_a += 1
        num_start_with_b += 1

elif min(num_end_with_a, num_start_with_b) == 0:
    if num_both >= 1:
        if num_end_with_a == 0:
            num_both -= 1
            num_end_with_a += 1
        
        if num_start_with_b == 0:
            num_both -= 1
            num_start_with_b += 1


if num_both > 0:
    total_ab += (num_both+1)
    num_end_with_a -= 1
    num_start_with_b -= 1


total_ab += min(num_start_with_b, num_end_with_a)

print(total_ab)
exit(0)

Solution (Python):
import re

N = int(input())

cnt = 0
tail_A = 0
head_B = 0
both = 0

for i in range(N):
    s = input()
    if s[0] == 'B':
        head_B += 1
    if s[-1] == 'A':
        tail_A += 1
    if s[0] == 'B' and s[-1] == 'A':
        both += 1
    matchedList = re.findall(r"AB", s)
    cnt += len(matchedList)

if tail_A == 0 and head_B == 0 and both == 0:
    cnt = cnt
elif tail_A == both and head_B == both:
    cnt += min(tail_A, head_B) - 1
else:
    cnt += min(tail_A, head_B)


print(cnt)

Solution (Python):
n = int(input())
s = []
ans = 0
c = [0, 0, 0]
for _ in range(n):
    tmp = input()
    if tmp[0] == "B" and tmp[-1] == "A":
        c[2] += 1
    elif tmp[0] == "B":
        c[1] += 1
    elif tmp[-1] == "A":
        c[0] += 1
    for i in range(len(tmp) - 1):
        if tmp[i:i+2] == "AB":
            ans += 1

p = min(c[:-1])
ans += p
p = max(c[:-1])-p
if c[0] == 0 and c[1] == 0:
    ans += max(c[2]-1, 0)
else:
    ans += c[2]
print(ans)

Solution (Python):

import sys


n = int(input())

strs = []

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


str_in_num = 0
str_both_ab = 0
str_head_a = 0
str_tail_b = 0

for st in strs:
    
    
    if len(st) > 2:
        str_in_num += st[0:-1].count('AB')

    
    if st[-1] == 'A' and st[0] == 'B':
        str_both_ab += 1
    else:
        if st[-1] == 'A':
            str_head_a += 1

        if st[0] == 'B':
            str_tail_b += 1

total = 0

if str_both_ab > 0:
    total += (str_both_ab - 1)

    if str_head_a > 0:
        total += 1
        str_head_a -= 1
    if str_tail_b > 0:
        total += 1
        str_tail_b -= 1

total += str_in_num
total += min(str_head_a, str_tail_b)

print(total)

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

b_a=0
_a=0
b_=0
ans=0

for i in range(N):
    s=input()
    if s[0]=='B' and s[-1]=='A':
        b_a+=1
    elif s[0]=='B':
        b_+=1
    elif s[-1]=='A':
        _a+=1

    for j in range(len(s)-1):
        if s[j]=='A'and s[j+1]=='B':
            ans+=1

if b_a>0:
    ans+=b_a-1
    if _a==0 and b_==0:
        print(ans)
    elif _a==1 and b_==0:
        print(ans+1)
    elif _a==1 and b_==0:
        print(ans+1)
    elif _a==1 and b_==1:
        print(ans+2)
    else:
        print(ans+2+min(_a-1,b_-1))
else:
    print(ans+min(_a,b_))

Solution (Python):




def main():
  lines = [input().strip() for _ in range(int(input()))]
  types = [(int(s[0] == 'B'), int(s[-1] == 'A')) for s in lines]
  count = sum(s.count('AB') for s in lines)

  before = sum(t[0] for t in types)
  after = sum(t[1] for t in types)

  if (0, 1) not in types:
    before -= 1

  if (1, 0) not in types:
    after -= 1

  before = max(before, 0)
  after = max(after, 0)

  print(count + min(before, after))


if __name__ == '__main__':
  main()

Solution (Python):
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()

n = ni()
_anum = 0
b_num = 0
banum = 0
ct = 0
for i in range(n):
    st = input()
    ct += st.count('AB')
    if st.startswith('B'):
        if st.endswith('A'):
            banum += 1
        else:
            b_num += 1
    else:
        if st.endswith("A"):
            _anum += 1
if banum > 0:
    if _anum > 0 and b_num > 0:
        print(ct + min(_anum - 1, b_num - 1) + (banum + 1))
    elif _anum == 0 and b_num == 0:
        print(ct + banum - 1)
    else:
        print(ct + banum)
else:
    print(ct + min(_anum, b_num))

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

import numpy as np

N = int(input())
S_list = [input().rstrip() for _ in range(N)]

S_ab_number = [i.count('AB') for i in S_list]
S_b_start_number = [1 if i[0] == 'B' and i[-1] != 'A' else 0 for i in S_list]
S_a_end_number = [1 if i[-1] == 'A' and i[0] != 'B' else 0 for i in S_list]
S_both_number = [1 if i[-1] == 'A' and i[0] == 'B' else 0 for i in S_list]

if sum(S_both_number) == 0:
    print(sum(S_ab_number) +  min(sum(S_b_start_number),sum(S_a_end_number)))
elif sum(S_b_start_number) == 0 and sum(S_a_end_number) != 0:
    print(sum(S_ab_number) + sum(S_both_number))
elif sum(S_b_start_number) != 0 and sum(S_a_end_number) == 0:
    print(sum(S_ab_number) + sum(S_both_number))
elif sum(S_b_start_number) == 0 and sum(S_a_end_number) == 0:
    print(sum(S_ab_number) + sum(S_both_number) - 1)
else:
    print(sum(S_ab_number) + sum(S_both_number) + 1 + min(sum(S_b_start_number)-1,sum(S_a_end_number)-1))

Solution (Python):
N = int(input())
s = [0 for i in range(N)]
for i in range(N):
    s[i] = input()
count = 0
Aowari = 0
Bhazimari = 0
ABtomoni = 0
for i in range(N):
    count += s[i].count('AB')
    if s[i][-1] == 'A' and s[i][0] == 'B':
        ABtomoni += 1
    elif s[i][-1] == 'A':
        Aowari += 1
    elif s[i][0] == 'B':
        Bhazimari += 1
if ABtomoni > 0:
    if Aowari >0 and Bhazimari >0:
        count += ABtomoni+1
        Aowari -= 1
        Bhazimari -= 1
    elif Aowari > 0 and Bhazimari == 0:
        count += ABtomoni
        Aowari -= 1
    elif Aowari == 0 and Bhazimari > 0:
        count += ABtomoni
        Bhazimari -= 1
    elif Aowari == 0 and Bhazimari == 0:
        count += ABtomoni-1
count += min(Aowari, Bhazimari)
print(count)

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

a = 0
b = 0
ab = 0
count = 0
for i in range(n):
  line = input()
  count += line.count("AB")
  if line[0] == "B" and line[-1] == "A":
    ab += 1
  elif line[0] == "B":
    b += 1
  elif line[-1] == "A":
    a += 1

if ab > 0:
  count += ab - 1
  if a > 0:
    count += 1
    a -= 1
  if b > 0:
    count += 1
    b -= 1
count += min([a, b])
print(count)

Solution (Python):

































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




ab_inner_count = 0
ab_top_bottom_count = 0
b_top_count = 0
a_bottom_count = 0
none_count = 0

for s_i in s:
    if s_i[0] == 'B' and s_i[-1] == 'A':
        ab_top_bottom_count += 1
    elif s_i[0] == 'B':
        b_top_count += 1
    elif s_i[-1] == 'A':
        a_bottom_count += 1
    else:
        none_count += 1

    for i in range(len(s_i) - 1):
        if s_i[i] == 'A' and s_i[i+1] == 'B':
            ab_inner_count += 1

ans = ab_inner_count

if ab_top_bottom_count == 0:
    ans += min(b_top_count, a_bottom_count)
elif a_bottom_count == 0:
    if b_top_count > 0:
        ans += ab_top_bottom_count
    else:
        ans += ab_top_bottom_count - 1
elif b_top_count == 0:
    if a_bottom_count > 0:
        ans += ab_top_bottom_count
    else:
        ans += ab_top_bottom_count - 1
else:
    ans += ab_top_bottom_count + 1
    ans += min(b_top_count - 1, a_bottom_count - 1)

print(ans)