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



Sample input:
3
ABCA
XBAZ
BAD


Sample output:
2

Submission status: Accepted

Solution code:
n = int(input())
s = [input() for _ in range(n)]
cnt = cnta = cntb = cntba =  0
for i in range(n):
    for j in range(len(s[i])-1):
        if s[i][j:j+2] == "AB":
            cnt += 1
    if s[i][0] == 'B' and s[i][-1] == 'A':
        cntba += 1
    elif s[i][0] == 'B':
        cntb += 1
    elif s[i][-1] == 'A':
        cnta += 1
if cnta == 0 and cntb == 0:
    print(max(0, cntba-1)+cnt)
elif cnta == 0 or cntb == 0:
    print(cntba+cnt)
else:
    print(cntba+1+min(cnta-1, cntb-1)+cnt)

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for i in range(N)]
ab = x_a = b_x = b_a = 0
for s in S:
    ab += s.count('AB')
    if s[-1]=='A' and s[0]=='B':
        b_a += 1
    elif s[-1]=='A':
        x_a += 1
    elif s[0]=='B':
        b_x += 1

ans = ab
if b_a:
    ans += b_a - 1
    if x_a:
        ans += 1
        x_a -= 1
    if b_x:
        ans += 1
        b_x -= 1

ans += min(x_a, b_x)
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
L=[input() for i in range(N)]
c=[0,0,0]
ans=0
for st in L:
  ans+=st.count("AB")
  if st[-1]=="A":
    if st[0]=="B":
      c[0]+=1
    else:
      c[1]+=1
  elif st [0]=="B":
    c[2]+=1
if c[0]!=0:
  ans+=c[0]-1
  if c[1]!=0:
    ans+=1
    c[1]-=1
  if c[2]!=0:
    ans+=1
    c[2]-=1
ans+=min(c[1:])
print(ans)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
def inpl(): return list(map(int, input().split()))

N = int(input())
A = 0
BA = 0
B = 0
Z = 0
ans = 0

for _ in range(N):
    s = input()
    ans += s.count("AB")
    if s[0] == "B":
        if s[-1] == "A":
            BA += 1
        else:
            B += 1
    elif s[-1] == "A":
        A += 1

if BA:
    ans += (BA - 1)
    if A:
        A -= 1
        ans += 1
    if B:
        B -= 1
        ans += 1

ans += min(A, B)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
strings = []
for i in range(N):
    strings.append(input())
ans = 0
acount = 0
bcount = 0
abcount = 0
for i in range(N):
    for j in range(len(strings[i])-1):
        if strings[i][j:j+2] == "AB":
            ans += 1
    if strings[i][0] == "B" and strings[i][-1] == "A":
        abcount += 1
    elif strings[i][0] == "B":
        bcount += 1
    elif strings[i][-1] == "A":
        acount += 1

if abcount > 0:
    ans += abcount-1
    if acount > 0:
        ans += 1
        acount -= 1
    if bcount > 0:
        ans += 1
        bcount -= 1
    ans += min(acount, bcount)
else:
    ans += min(acount, bcount)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())

ans = 0
A = []
B = []
for i in range(N):
    si = input()
    for j in range(len(si)-1):
        if si[j] == 'A' and si[j+1] == 'B':
            ans += 1
    if si[0] == 'B':
        B.append(i)
    if si[len(si)-1] == 'A':
        A.append(i)
    
if len(A) != 0 and len(A) == len(B) == len(set(A)&set(B)):
    print(ans+len(A)-1)
else:
    print(ans+min(len(A),len(B)))

Submission status: Accepted

Solution code:
N = int(input())
a = []
ans = 0
BA = 0
B = 0
A = 0
for i in range(N):
  x = input()
  for j in range(len(x)-1):
    if x[j] == "A" and x[j+1] == "B":
      ans += 1
  if x[0] == "B" and x[-1] == "A":
    BA += 1
  elif x[0] == "B":
    B += 1
  elif x[-1] == "A":
    A += 1
if BA != 0:
  ans += (BA-1)
  if A != 0 and B != 0:
    ans += (min(A,B)+1)
  elif A == 0 and B == 0:
    ans = ans
  else:
    ans += 1
else:
  ans += min(A,B)
print(ans)

Submission status: Accepted

Solution code:
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]))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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())

Submission status: Accepted

Solution code:
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')

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#!/usr/bin/env 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'))


# region fastio

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

# endregion

if __name__ == "__main__":
    main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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
#print(ans)
#print(a,b,ba)
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)
#print(a,b,ba)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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]
    # print(r,ss)

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


print(main())

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Runtime Error

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

ab = 0
ba = 0
c2 = 0
c3 = 0
for x in s:
    if 'AB' in x:
        ab += x.count('AB')    
    if x[-1] == 'A' and x[0] == 'B':
        ba = 1
    if x[-1] == 'A' and x[0] != 'B':
        c2 += 1
    if x[-1] != 'A' and x[0] == 'B':
        c3 += 1
if ba > 0:
    if c2 + c3 > 0:
        ans = ab + ba + min(c2, c3)
    else: # c2 = c3 =0
        ans = ab + ba - 1
print(ans)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import collections as cl
import sys


def II():
    return int(sys.stdin.readline())


def MI():
    return map(int, sys.stdin.readline().split())


def LI():
    return list(map(int, sys.stdin.readline().split()))


def main():
    N = II()

    words = []
    starts_with_B = 0
    end_with_A = 0
    contain_AB = 0
    starts_with_B_and_end_with_A = 0
    for i in range(N):
        word = input()
        words.append(word)
        contain_AB += len(word) - len(word.replace("AB", "_"))

        if word[0] == "B" and word[-1] == "A":
            starts_with_B_and_end_with_A += 1
        elif word[0] == "B":
            starts_with_B += 1
        elif word[-1] == "A":
            end_with_A += 1

    if starts_with_B_and_end_with_A == 0:
        print(contain_AB + min(starts_with_B, end_with_A))
        return

    min_A_or_B = min(starts_with_B, end_with_A)
    amari = abs(starts_with_B - end_with_A)
    contain_AB += min_A_or_B

    if amari == 0:
        print(contain_AB)

    if amari >= starts_with_B_and_end_with_A:
        print(contain_AB + starts_with_B_and_end_with_A)
    else:
        available = starts_with_B_and_end_with_A // amari
        contain_AB += available * amari
        starts_with_B_and_end_with_A = starts_with_B % amari
        print(contain_AB + starts_with_B_and_end_with_A)


main()

Submission status: Runtime Error

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

Submission status: Runtime Error

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

# 文字列にABが入ってる数 + 組み合わせて入る数
# 文字列にABが入ってる数 + f(Aで終わる数, Bで始まる数, Bで始まりAで終わる数)
include = 0
sb = 0
fa = 0
sbfa = 0
for s in S:
    if 'AB' in s:
        include += 1
    if s[0] == 'B' and s[-1] == 'A':
        sbfa += 1
    elif s[0] == 'B':
        sb += 1
    elif s[-1] == 'A':
        fa += 1

def calc_comb(sb, fa, sbfa):
    ans = 0
    if sbfa > 0:
        ans += sbfa-1
        if sb > 0:
            sb -= 1
            ans += 1
        if fa > 0:
            fa -= 1
            ans += 1
    ans += min(sb, fa)

print(include + calc_comb(sb, fa, sbfa))

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
using namespace std;
#define rep(i, s, e) for (int i = s; i < e; ++i)
#define sort_(a) stable_sort(a.begin(), a.end())
#define rsort(a) stable_sort(a.rbegin(), a.rend())
#define sum(a) accumulate(a.begin(), a.end(), 0LL)
#define join(a, d) accumulate(a.begin() + 1, a.end(), a[0], [](string s, string t) {return s + d + t;})
#define all(a) a.begin(), a.end()
// #define __lcm(a, b) std::__detail::__lcm(a, b)
typedef long long ll;
const long mod = 1e9 + 7;

int find_all(const string str, const string subStr) {
  int result = 0;
  int subStrSize = subStr.size();
  size_t pos = str.find(subStr);
  while (pos != string::npos) {
    ++result;
    pos = str.find(subStr, pos + subStrSize);
  }
  return result;
}

int main(void) {
#ifdef DEBUG
  freopen("input.txt", "r", stdin);
#endif

  ios_base::sync_with_stdio(false);
  cin.tie(0);

  int N;
  cin >> N;
  vector<string> S(N);
  rep(i, 0 ,N) cin >> S[i];
  int ans = 0;
  int _A = 0;
  int B_ = 0;
  int BA = 0;
  rep(i, 0, N) {
    ans += find_all(S[i], "AB");
    if (S[i][0] == 'B' && S[i].back() == 'A')
      BA += 1;
    else if (S[i][0] == 'B')
      B_ += 1;
    else if (S[i].back() == 'A')
      _A += 1;
  }
  if (abs(_A - B_) >= BA) {
    ans += min(_A, B_);
    ans += BA;
  } else {
    ans += max(_A, B_);
    BA -= abs(_A - B_);
    ans += BA / 2;
    ans += BA % 2;
  }
  cout << ans << endl;
  return 0;
}

Submission status: Runtime Error

Solution code:
n = int(input())

ans = 0
last_a = 0
first_b = 0
cnt = 0

for i in range(n):
    s = input()
    ans += s.count("AB")
    if s[-1] == "A":
        last_a += 1
    if s[0] == "B":
        first_b += 1
    if s[-1] == "A" and s[0] == "B":
        cnt += 1

if last_a == last_b:
    ans += min(last_a, last_b) - 1
else:
    ans += min(last_a, last_b)

print(ans)

Submission status: Runtime Error

Solution code:
n = int(input())

a_end = 0
b_start = 0
a_b = 0
cnt = 0

for _ in range(n):
    s = input()
    cnt += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        a_b += 1
        continue
    if s[0] == "B":
        b_start += 1
    if s[-1] == "A":
        a_end += 1

if a_end == 0 and b_start == 0:
    tmp = max(a_b - 1, 0)
else:
    tmp = min(a_end + b_start) + a_b
print(cnt + tmp)

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
from math import sqrt, gcd
def input(): return sys.stdin.readline()[:-1] # warning not \n
# def input(): return sys.stdin.buffer.readline()[:-1]

# n = int(input())



def solve():
    n = int(input())
    ans = 0
    a = 0
    b = 0
    for _ in range(n):
        s = input()
        a += s[-1] == 'A'
        b += s[0] == 'B'
        ans += s.replace('AB', "*").count('*')
    print(ans + min(a, b))
    

t = 1
# t = int(input())
for case in range(1,t+1):
    ans = solve()




"""




"""

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import defaultdict, deque
from math import sqrt, gcd
def input(): return sys.stdin.readline()[:-1] # warning not \n
# def input(): return sys.stdin.buffer.readline()[:-1]

# n = int(input())



def solve():
    n = int(input())
    ans = 0
    a = 0
    b = 0
    for _ in range(n):
        s = input()
        a += s[-1] == 'A'
        b += s[0] == 'B'
        ans += s.replace('AB', "*").count('*')
    print(ans + min(a, b))
    

t = 1
# t = int(input())
for case in range(1,t+1):
    ans = solve()




"""




"""

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import defaultdict, deque
from math import sqrt, gcd, factorial
def input(): return sys.stdin.readline()[:-1] # warning not \n
# def input(): return sys.stdin.buffer.readline()[:-1]

# n = int(input())



def solve():
    n = int(input())
    ans = 0
    a = 0
    b = 0
    for _ in range(n):
        s = input()
        a += s[-1] == 'A'
        b += s[0] == 'B'
        ans += s.replace('AB', "*").count('*')
    print(ans + min(a, b))
    

t = 1
# t = int(input())
for case in range(1,t+1):
    ans = solve()




"""




"""

Submission status: Runtime Error

Solution code:
n = int(input())
res = 0
sboth = 0
sa = 0
sb = 0
for i in range(n):
    s = input()
    res += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        sboth += 1
        continue
    if s[0] == "B":
        sb += 1
        continue
    if s[-1] == "A":
        sa += 1
        continue

num = min(sboth)
res += num
sboth -= num

num = min(sboth, sb)
res += num
sboth -= num

num = min(sa, sb)
res += num
sa -= num
sb -= num

num = min(sboth)
res += num
sboth -= num

num = min(sboth, sb)
res += num
sboth -= num

num = min(sa, sb)
res += num
sa -= num
sb -= num


if sboth > 0:
    sboth = 1
    res += sboth - 1

print(res)

Submission status: Runtime Error

Solution code:
n = int(input())
r = 0
a = 0
b = 0
for _i in range(n):
    s = input()
    r += s.count("AB")
    B = 0
    if s[-1]=="A":
        if b > 0:
            b -= 1
            r += 1
        else:
            A += 1
    if s[0]=="B":
        if a > 0:
            a -= 1
            r += 1
        else:
            B += 1
    a += A
    b += B


print(r)

Submission status: Runtime Error

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

cnt = 0
end_a = 0
sta_b = 0
a_b = 0
for s in S:
    cnt += s.count('AB')
    if s[-1]=='A' and s[0]=='B':
        a_b += 1
    elif s[-1]=='A':
        end_a += 1
    elif s[0]=='B':
        sta_b += 1

a_b = [a_b, a_b]
if a_b[0]>=end_a:
    cnt += end_a
    a_b[0] -= end_a
    end_a = 0
else:
    cnt += a_b
    a_b[0] = 0
    end_a -= a_b

if a_b[1]>=sta_b:
    cnt += sta_b
    a_b[1] -= sta_b
    sta_b = 0
else:
    cnt += a_b
    a_b[1] = 0
    sta_b -= a_b
cnt += min(end_a, sta_b)
cnt += min(a_b)
print(cnt)