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 = []
for i in range (N):
    S.append(input())

ab_count = 0
bottom_a = 0
top_b = 0
ba = 0
for s in S:
    if s[-1] == 'A' and s[0] == 'B':
        ba += 1
    else:
        if s[-1] == 'A':
            bottom_a += 1
        if s[0] == 'B':
            top_b += 1
    for i in range(1,len(s)):
        if s[i-1] == 'A' and s[i] == 'B':
            ab_count += 1
if ba > 0:
    if bottom_a > 0:
        bottom_a -= 1
        ab_count += 1
    if top_b > 0:
        top_b -=  1
        ab_count += 1
ans = max(ba - 1, 0) + min(bottom_a, top_b) + ab_count
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
ls=[input() for i in range(N)]
org_num=0
XA_num=0
BA_num=0
BX_num=0

for i in ls:
    org_num+=i.count('AB')
    listed_word=list(i)
    if listed_word[0]=='B' and listed_word[-1]=='A':
        BA_num+=1
    elif listed_word[0]=='B':
        BX_num+=1
    elif listed_word[-1]=='A':
        XA_num+=1
#print("組み合わせ前のAB個数は",org_num,'個')
#print("X~Aは",XA_num,"個.B~Aは",BA_num,"個.B~Xは",BX_num,"個")

if BX_num:
    BX_num_addition=1
else:
    BX_num_addition=0

if XA_num:
    answer=org_num+BA_num+BX_num_addition
elif BA_num:
    answer=org_num+BA_num+BX_num_addition-1
else:
    answer=org_num

XA_num-=1
BX_num-=1

shiage=min(XA_num,BX_num)
if shiage<0:
    shiage=0

answer+=shiage
print(answer)

Submission status: Accepted

Solution code:
#問題C
N = int(input())

naka=0
a_kazu=0
b_kazu=0
b_a_kazu=0
for i in range(N):
    a = str(input())
    naka+=a.count("AB")
    if (a[0]=="B" and a[-1]=="A"):
        b_a_kazu+=1
    elif a[0]=="B":
        b_kazu+=1
    elif a[-1]=="A":
        a_kazu+=1
if b_a_kazu==0:
    print(naka+min(a_kazu, b_kazu))
else:
    if (a_kazu==0 and b_kazu==0):
        print(naka+(b_a_kazu-1))
    elif (a_kazu==0 or b_kazu==0):
        print(naka+(b_a_kazu))
    else:
        print(naka+(b_a_kazu-1)+min(a_kazu+1, b_kazu+1))

Submission status: Accepted

Solution code:
N=int(input())

naiv=0
endsA=0
startsB=0
both=0

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

# print("endsA {}".format(endsA))
# print("startsB {}".format(startsB))
# print("both {}".format(both))
# print("naiv {}".format(naiv))

res=naiv
if both >= startsB and both >= endsA and (endsA > 0 and startsB > 0):
    lower = min(endsA, startsB)
    higher = max(endsA, startsB)
    res += lower*2
    both -= lower
    startsB -= lower
    endsA -= lower
    res += both
    both = 0
elif both <= startsB and both <= endsA:
    res += both*2
    endsA -= both
    startsB -= both
    both = 0
    res += min(endsA, startsB)
# まんなか
elif both > 0 and max(endsA, startsB) > 0:
    lower = min(endsA, startsB)
    res += 2*lower
    both -= lower
    endsA -= lower
    startsB -= lower
    res += both
elif both > 0 and max(endsA, startsB) == 0:
    res += both-1
else:
    res += min(endsA, startsB)

print(res)

Submission status: Accepted

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

top = [0 for _ in range(N)]
last = [0 for _ in range(N)]

res = 0
n = 0
for s in S:
    for i in range(len(s)-1):
        if s[i] == 'A' and s[i+1] == 'B':
            res += 1
            
    if s[0] == 'B':
        top[n] = 1
        
    if s[-1] == 'A':
        last[n] = 1
        
    n += 1
 
d = 0
t = 0
l = 0
for i in range(N):
    if top[i] == 1 and last[i] == 1:
        d += 1
    elif top[i] == 1:
        t += 1
    elif last[i] == 1:
        l += 1
     

if d >= 1:
    res += d - 1



if d > 0 and min(t, l) >= 1:
    res += min(t-1, l-1)
    res += 2
    
elif d > 0 and min(t, l) < 1 and max(t, l) >= 1:
    res += 1
    
else:
    res += min(t, l)
    
    
print(res)

Submission status: Accepted

Solution code:
n = int(input())
inab = 0
topb = 0
taila = 0
topb_taila = 0
for _ in range(n):
    s = str(input())
    if (s[0] == "B")&(s[-1] == "A"):
        topb_taila += 1
    else:
        if (s[0] == "B"):
            topb += 1
        if (s[-1] == "A"):
            taila += 1
    
    bef =""
    for i in range(len(s)):
        if (bef=="A")&(s[i]=="B"):
            inab += 1
        bef = s[i]

ans = inab

topb += topb_taila
taila += topb_taila

if topb==taila:
    if topb==topb_taila:
        if topb==0:
            ans+=0
        else:
            ans += topb-1
    else:
        ans += topb
else:
    ans += min(topb,taila)

print(ans)

Submission status: Accepted

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

a = 0
b = 0
b_a = 0
ab = 0
for j in range(N):
    if s[j][0] == 'B':
        b += 1
    if s[j][-1] == 'A':
        a += 1
    
    if s[j][0] == 'B' and s[j][-1] == 'A':
        b_a += 1

    ab += s[j].count('AB')

if b_a >= 1 and b_a == a and b_a == b:
    print(ab + a - 1)
else:
    print(ab + min(a,b))

Submission status: Accepted

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

count = 0
count_BA = 0
count_A = 0
count_B = 0
for i in range(N):
    count += s[i].count('AB')
    if s[i][0] == 'B' and s[i][-1] == 'A':
        count_BA += 1
    elif s[i][0] == 'B':
        count_B += 1
    elif s[i][-1] == 'A':
        count_A += 1

if count_B != 0 and count_A != 0:
    print(count + count_BA - 1 + 1 + 1 + min(count_A, count_B) - 1)
elif count_B != 0 or count_A != 0:
    print(count + count_BA - 1 + 1)
elif count_BA != 0:
    print(count + count_BA - 1)
else:
    print(count)

Submission status: Accepted

Solution code:
N = int(input())
a, b, ab, ret = 0, 0, 0, 0
for i in range(N):
    s = input()
    l = len(s) - 1
    if s[0] == "B" and s[l] == "A":
        ab += 1
    if s[0] == "B":
        b += 1
    if s[l] == "A":
        a += 1
    ret += s.count("AB")
if a == b and a == ab and a > 0:
    a -= 1
ab = min(a,b)
print(ret + ab)

Submission status: Accepted

Solution code:
def ab_substrings(N: int, S: list)->int:
    res = 0
    endA = 0
    startB = 0
    both = 0

    for s in S:
        res += s.count('AB')
        if s.endswith('A'):
            if s.startswith('B'):
                both += 1
            else:
                endA += 1
        elif s.startswith('B'):
            startB += 1

    if both > 0:
        res += both - 1

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

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

    return res + min(endA, startB)


if __name__ == "__main__":
    N = int(input())
    S = [input() for _ in range(N)]

    ans = ab_substrings(N, S)
    print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = []
ab = []  # if include ab [num, ,] if b start [, 1], if a end [, ,1]
for i in range(N):
    S.append(input())

ab_num = 0

"""
b_start = 0
a_end = 0
for i in range(N):
    s = S[i]
    for j in range(1, len(s)):
        if s[j] == 'B' and s[j-1] == 'A':
            ab_num += 1
    if s[0] == 'B':
        b_start += 1
    if s[len(s)-1] == 'A':
        a_end += 1

print(ab_num + min(a_end, b_start))


BABA
ABABA
BAABBAAB
BBAAAAB
ABABABAB
"""

x_A = 0
B_A = 0
B_x = 0


for i in range(N):
    s = S[i]
    for j in range(1, len(s)):
        if s[j] == 'B' and s[j-1] == 'A':
            ab_num += 1

    if s[0] == 'B':
        if s[len(s) - 1] == 'A':
            B_A += 1
        else:
            B_x += 1
    elif s[len(s) - 1] == 'A':
        x_A += 1

if B_A > 0:
    if x_A * B_x > 0:
        print(ab_num + B_A-1 + 2 + min(x_A-1, B_x-1))
    else:
        if x_A + B_x > 0:
            print(ab_num + B_A)
        else:
            print(ab_num + B_A-1)
else:
    print(ab_num + min(x_A, B_x))

Submission status: Accepted

Solution code:
N=int(input())
s=[input() for _ in range(N)]
def checkAB(si):
  cnt=0
  for i in range(len(si)-1):
    if si[i]=='A' and si[i+1]=='B':cnt+=1
  return cnt

ABin=sum([checkAB(si) for si in s])
Aend=sum([si[len(si)-1]=='A' for si in s])
Bstart=sum([si[0]=='B' for si in s])
BstrA=sum([si[0]=='B' and si[len(si)-1]=='A' for si in s])
#print(ABin,Aend,Bstart)
if BstrA==Aend and BstrA==Bstart and BstrA>0:
  ans=ABin+BstrA-1
else:
  ans=ABin+min(N-1,Aend,Bstart)
print(ans)

Submission status: Accepted

Solution code:

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

cnt = 0
b, a = 0, 0
ab = 0
for s in S:
  cnt += 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
if ab > 1:
  cnt += ab-1
  ab = 1
if ab:
  if a:
    cnt += 1
    a -= 1
  if b:
    cnt += 1
    b -= 1
at = 0
bt = 0
while a > 0 and b > 0:
  if a:
    at += 1
    a -= 1
  if b:
    bt += 1
    b -= 1
  if at + bt == 2:
    cnt += 1
  at = 0
  bt = 0
print(cnt)

Submission status: Accepted

Solution code:
N = int(input())
slist = [input() for _ in range(N)]
cnt = 0
bnum = 0
anum = 0
banum = 0
for s in slist:
    cnt+= s.count('AB')
    if s[0]=='B':
        bnum+=1
        if s[-1]=='A':
            banum+=1
    if s[-1]=='A':
        anum+=1
if banum == anum == bnum:
    if banum==0:
        print(cnt)
    else:
        print(cnt+banum-1)
else:
    print(cnt+min(bnum,anum))

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for i in range(N)]
count = 0
con = []
Alis = []
Blis = []
for s in S:
    count += s.count('AB')
for i in range(N):
    if S[i][-1:] == 'A' and S[i][0] == 'B':
        con.append(S[i])
    elif S[i][-1:] == 'A':
        Alis.append(S[i])
    elif S[i][0] == 'B':
        Blis.append(S[i])
if len(Alis)== 0 and len(Blis) == 0 and len(con) > 0:
    count += len(con)-1
else:
    count += min(len(con)+len(Alis),len(con)+len(Blis))
print(count)

Submission status: Accepted

Solution code:
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
N = int(input())
ls =[]
for _ in range(N):
    ls.append(input())

count = 0
for i in  ls:
    count += i.count('AB')

countB =0
countA = 0
countBA = 0
for i in ls:
    if i[0] == 'B' and i[-1] == 'A':
        countBA += 1
    elif i[0] == 'B':
        countB += 1
    elif i[-1] == 'A':
        countA += 1

if countBA ==0:
    count += min(countA,countB)
elif countA ==0 and countB == 0:
    count += countBA-1
elif countA == 0 or countB ==0:
    count += countBA
else:
    count += countBA + min (countA,countB)


print(count)

Submission status: Accepted

Solution code:
#d=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
#import numpy as np
#n=int(input())
#li=input().split()
#import fractions
#lis=list(map(int,input().split()))

n=int(input())
S=[]
ans=0
firstB,lastA,bothAB=0,0,0

for i in range(n):
    S.append(input())
    flag=0
    for j in range(len(S[-1])-1):
        if S[-1][j:j+2]=="AB":
            ans+=1
    if S[-1][0]=="B":
        firstB+=1
        flag+=1
    if S[-1][-1]=="A":
        lastA+=1
        flag+=1
    if flag==2:
        bothAB+=1
        firstB-=1
        lastA-=1

if firstB==lastA:
    if firstB==0 and bothAB!=0:
        ans+=bothAB-1
    else:
        ans+=(bothAB+firstB)
else:
    ans+=min(firstB,lastA)+bothAB

print(ans)

Submission status: Accepted

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

center = 0
s_aend = []
s_bstart = []
s_bsae = []
s_else = []
center = 0

for s in s_:
  if s.startswith("B") and s.endswith("A"):
    s_bsae.append(s)
  elif s.startswith("B"):
    s_bstart.append(s)
  elif s.endswith("A"):
    s_aend.append(s)
  else:
    center += s.count("AB")

s_max = ""
if len(s_bsae) > 0:
  s_max = ''.join(s_bsae)

if len(s_bstart) > 0 and len(s_bsae) > 0:
  center += 1
  b_len = len(s_bstart)-1
else:
  b_len = len(s_bstart)
  
if len(s_aend) > 0 and len(s_bsae) > 0:
  center += 1
  a_len = len(s_aend)-1
else:
  a_len = len(s_aend)

a_center = 0
b_center = 0

for s in s_bstart:
  a_center += s.count("AB")
for s in s_aend:
  b_center += s.count("AB")

#print(s_max.count("AB"))
#print(center)
#print(min(a_len,b_len))
#print(a_center)
#print(b_center)
print(s_max.count("AB") + center + min(a_len,b_len)+a_center+b_center)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

N = int(raw_input())
S = list()

_count = 0
_A = 0
_B = 0
_BA = 0
for i in range(N):
    S.append(raw_input())

for s in S:
    if s[-1] == "A":
        _A += 1
    if s[0] == "B":
        _B += 1
    if s[-1] == "A" and s[0] == "B":
        _BA += 1
    for i in range(len(s)-1):
        if s[i:i+2] == "AB":
            _count += 1
    
_count += min(_A,_B)
if _A == _B == _BA != 0:
    _count -= 1

print str(_count)

Submission status: Accepted

Solution code:
n = int(input())
s = []
count = 0
boa = 0
boo = 0
ooa = 0
for _ in range(n):
  i = input()
  s += [i]
  l = len(i)
  for k in range(l-1):
    if i[k:k+2] == 'AB':
      count += 1
  if i[0] == 'B' and i[-1] == 'A':
    boa += 1
  elif i[0] == 'B':
    boo += 1
  elif i[-1] == 'A':
    ooa += 1
if boo==0 and ooa==0 and boa!=0:
  rest = boa-1
else:
  rest = boa + min(boo,ooa)
print(count+rest)

Submission status: Accepted

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

count_AB = 0
lefter_B = 0
righter_A = 0
only_lefter_B = 0
only_righter_A = 0
for i in range(N):
    count_AB += S[i].count('AB')
    if S[i][0] == 'B':
        lefter_B += 1
    if S[i][len(S[i])-1] == 'A':
        righter_A += 1
    if (S[i][0] == 'B')and(S[i][len(S[i])-1] != 'A'):
        only_lefter_B += 1
    if (S[i][0] != 'B')and(S[i][len(S[i])-1] == 'A'):
        only_righter_A += 1
        
if (only_lefter_B==0) and (only_righter_A==0):
    Appearing_AB = max(min(lefter_B,righter_A) - 1 , 0)
else:
    Appearing_AB = min(lefter_B,righter_A)


print(count_AB + Appearing_AB)

Submission status: Accepted

Solution code:
N = int(input())
sum = 0
sum_a = 0
sum_b = 0
sum_ab = 0
for i in range(N):
  s = input()
  sum += s.count('AB')
  if (s[-1] == 'A' and s[0] == 'B'):
    sum_ab += 1
  elif (s[0] == 'B'):
    sum_b += 1
  elif (s[-1] == 'A'):
    sum_a += 1
alpha = 0
if (sum_a == 0 and sum_b == 0 and sum_ab > 0):
  alpha = sum_ab - 1
else:
  alpha = min(sum_a, sum_b) + sum_ab
print(sum + alpha)

Submission status: Accepted

Solution code:
n=int(input())
s=[]
for i in range(n):
  s.append(input())
cnt_a=0
cnt_b=0
cnt_ab=0
for j in range(n):
  if s[j][0]=='B' and s[j][len(s[j])-1]=='A':
    cnt_ab+=1
  elif s[j][0]=='B':
    cnt_b+=1
  elif s[j][len(s[j])-1]=='A':
    cnt_a+=1
cnt_a+=cnt_ab
cnt_b+=cnt_ab
cnt_2=0
for l in range(n):
  cnt_2+=s[l].count('AB')
if cnt_a==0 and cnt_b==0:
  print(cnt_2)
elif cnt_ab-cnt_a==0 and cnt_ab-cnt_b==0:
  print((cnt_ab+cnt_2)-1)
else:
  print(min(cnt_a,cnt_b)+cnt_2)

Submission status: Accepted

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

hd = 0
tl = 0
bt = 0
ans = 0
for s in S:
    for i in range(len(S)-1):
        if s[i:i+2] == 'AB':
            ans += 1
    if s[0] == 'B' and s[-1] == 'A':
        bt += 1
    elif s[0] == 'B':
        hd += 1
    elif s[-1] == 'A':
        tl += 1

if bt == 0:
    ans += min(hd, tl)
else:
    ans += bt - 1
    if hd > 0 and tl > 0:
        ans += 2 + min(hd-1, tl-1)
    elif hd > 0 or tl > 0:
        ans += 1

print(ans)

Submission status: Accepted

Solution code:
n=int(input())
count=0
dual=0
startb=0
enda=0

f0=0
f1=0
f2=0

for i in range(n):
    tmp=list(input())
    if tmp[0]=="B" and tmp[-1]=="A":
        #dual+=1
        f0+=1
        startb+=1
        enda+=1
    elif tmp[0]=="B":
        startb+=1
        f1+=1
    elif tmp[-1]=="A":
        enda+=1
        f2+=1

    aflag=0
    for t in tmp:
        if aflag==1 and t=="B":
            count+=1
            aflag=0
        elif t=="A":
            aflag=1
        else:
            aflag=0
"""
while dual>0:
    if startb>enda:
        enda+=1
    else:
        startb+=1
    dual-=1
"""
count+=min(startb,enda)

#補正
if f1 ==0 and f2==0 and f0>0:
    count-=1
if count<0:
    count=0

print(count)

Submission status: Accepted

Solution code:
N = int(input())
A = 0
B = 0
BA = 0
ans = 0
for _ in range(N):
    S = input()
    for i in range(len(S) - 1):
        if S[i : i + 2] == 'AB':
            ans += 1
    if S[0] == 'B' and S[-1] == 'A':
        BA += 1
    elif S[0] == 'B':
        B += 1
    elif S[-1] == 'A':
        A += 1
    # print(S, A, B, BA, ans)

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

Submission status: Accepted

Solution code:
n=int(input())
s=[]
cnt=0
c=[0,0,0]
for i in range(n):
  a=input()
  if a[0]=="B":
    c[0]+=1
  if a[-1]=="A":
    c[1]+=1
  if a[0]=="B" and a[-1]=="A":
    c[2]+=1
  for j in range(len(a)-1):
    if a[j]=="A" and a[j+1]=="B":
      cnt+=1
      #print("cnt",cnt)
if c[0]==0 and c[1]==0:
  plus=0
elif c[0]==c[1] and c[1]==c[2]:
  plus=c[2]-1
else:
  plus=min(c[0],c[1])
print(cnt+plus)

Submission status: Accepted

Solution code:
n=int(input())
ls=[0]*n
for i in range(n):
    ls[i]=input()
numab=0
sA=0
sB=0
sBA=0
for i in range(n):
    sb=""
    for j in ls[i]:
        if sb=="A":
            if j=="B":
                numab+=1
        sb=j
    if ls[i][0]=="B":
        if ls[i][-1]=="A":
            sBA+=1
        else:
            sB+=1
    if ls[i][-1]=="A" and ls[i][0]!="B":
        sA+=1
ans=0
if sA!=0 and sB!=0:
    ans=sBA+1+min(sA-1,sB-1)
elif sA==0 and sB!=0:
    ans=sBA
elif sB==0 and sA!=0:
    ans=sBA
else:
    ans=sBA-1
if ans<0:
    ans=0
ans+=numab
#print(numab,sB,sA,sBA)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
s = [0]*N
num_ab_in = 0
num_hip_a = 0
num_head_b =0 
num_both = 0

for i in range(N):
    s[i] = input()
    slist= list(s[i])
    num_ab_in += s[i].count('AB')
    if slist[0] =='B':
        num_head_b +=1
    if slist[-1] =='A':
        num_hip_a +=1
    if slist[0] =='B' and slist[-1] =='A':
        num_both +=1

if num_both == num_head_b and num_both == num_hip_a and num_both !=0:
    ans = num_ab_in + num_both-1
else:
    ans = num_ab_in + min(num_head_b,num_hip_a)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = [None] * N
for i in range(N):
    S[i] = input()

ans = 0
endswith_a = 0
startswith_b = 0
both_ab = 0
for s in S:
    ans += s.count('AB')
    a = s.endswith('A')
    b = s.startswith('B')
    endswith_a += 1 if a else 0
    startswith_b += 1 if b else 0
    both_ab += 1 if a and b else 0

if both_ab == endswith_a or both_ab == startswith_b:
    if endswith_a == startswith_b and both_ab > 0:
        ans += both_ab - 1
    else:
        ans += both_ab
else:
    ans += min(endswith_a, startswith_b)

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
count = 0
ca = 0
cb = 0
cab = 0
for i in range(N):
    si = input()
    for j in range(len(si)-1):
        if si[j] == "A" and si[j+1] == "B":
            count += 1
    if si[-1] == "A" and si[0] == "B":
        cab += 1
    else:
        if si[-1] == "A":
            ca += 1
        if si[0] == "B":
            cb += 1
    
#print(count)
if cab == 0:
    count += min(ca, cb)
elif ca == 0 and cb == 0:
    count += cab - 1
elif (ca == 0 and cb != 0) or (ca != 0 and cb == 0):
    count += cab
else:
    count += cab + min(ca, cb)

#print(ca, cb, cab)

print(count)

Submission status: Accepted

Solution code:
from collections import deque

n = int(input())
a = []
firstB = deque()
lastA = deque()
both = deque()
used = set()
for i in range(n):
    s = input().strip()
    a.append(s)
    if s[0] == 'B' and s[-1] == 'A':
        both.append(i)
        used.add(i)
    elif s[0] == 'B':
        firstB.append(i)
        used.add(i)
    elif s[-1] == 'A':
        lastA.append(i)
        used.add(i)

ret = ''
while both:
    ret += a[both.pop()]
if ret and lastA:
    ret = a[lastA.pop()] + ret
if ret and firstB:
    ret += a[firstB.pop()]
while lastA and firstB:
    ret += a[lastA.pop()] + a[firstB.pop()]
while lastA:
    ret += a[lastA.pop()]
while firstB:
    ret += a[firstB.pop()]
for i in range(n):
    if i not in used:
        ret += a[i]
print(ret.count('AB'))

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for _ in range(N)]
mae_B = 0
ushiro_A = 0
docchimo = 0
naka_AB = 0
for s in S:
    for i in range(len(s)-1):
        if s[i] == 'A' and s[i+1] == 'B':
            naka_AB += 1
    if s[0] == 'B' and s[-1] == 'A':
        docchimo += 1
    elif s[0] == 'B':
        mae_B += 1
    elif s[-1] == 'A':
        ushiro_A += 1
ans = naka_AB
ans += max(0, docchimo-1)
if docchimo > 0:
    if mae_B > 0:
        mae_B -= 1
        ans += 1
    if ushiro_A > 0:
        ushiro_A -= 1
        ans += 1
ans += min(mae_B, ushiro_A)
print(ans)

Submission status: Accepted

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

    AB = 0
    B_ = 0
    _A = 0
    B_A = 0
    for ss in s:
        for i in range(len(ss)-1):
            if ss[i:i+2] == 'AB':
                AB += 1
        if ss[0] == 'B':
            if ss[-1] == 'A':
                B_A += 1
            else:
                B_ += 1
        elif ss[-1] == 'A':
            _A += 1
    if B_A > 0:
        if _A > 0 and B_ > 0:
            print(AB + (B_A - 1) + 2 + min(_A - 1, B_ - 1))
        elif _A == 0 and B_ == 0:
            print(AB + (B_A - 1))
        else:
            print(AB + (B_A - 1) + 1)
    else:
        print(AB + min(_A, B_))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
count_BA = 0
count_A = 0
count_B = 0
for i in range(n):
    s = input()
    ans += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        count_BA += 1
    elif s[0] == "B":
        count_B += 1
    elif s[-1] == "A":
        count_A += 1

if count_BA > 0:
    ans += count_BA - 1
if count_BA > 0 and count_B > 0:
    ans += 1
    count_B -= 1
if count_BA > 0 and count_A > 0:
    ans += 1
    count_A -= 1
while count_A > 0 and count_B > 0:
    ans += 1
    count_A -= 1
    count_B -= 1

print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

#print(N, S)

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

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)

Submission status: Accepted

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

#print(lis1)
#print(lis2)
#print(lis3)
#print(lis4)

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)

    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)

    print(ct + p + q)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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
 
 
#print(ans,end_A,start_B,same_time)
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))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

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)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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