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:
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(input())
def S(): return list(input())
n=I()
ans=0
sb=0
fa=0
sbfa=0
for i in range(n):
    ts=S()
    if ts[0]=="B" and ts[-1]!="A":
        sb+=1
    elif ts[0]!="B" and ts[-1]=="A":
        fa+=1
    elif ts[0]=="B" and ts[-1]=="A":
        sbfa+=1
    for i in range(len(ts)-1):
        if ts[i]=="A" and ts[i+1]=="B":
            ans+=1
    
p=min(fa,sb,sbfa)
ans+=2*p
if p>0:
    ans+=sbfa-p+min(max(0,fa-p),max(0,sb-p))
else:
    if sbfa==0:
        ans+=min(max(0,fa-p),max(0,sb-p))
    elif sb==0:
        if fa>sbfa:
            ans+=sbfa
        else:
            ans+=sbfa-1+min(1,fa)
    elif fa==0:
        if sb>sbfa:
            ans+=sbfa
        else:
            ans+=sbfa-1+min(1,sb)   
print(ans)

Submission status: Accepted

Solution code:
n = int(input())

ans = 0
b = 0
a = 0
ab = 0
for j in range(n):
     s = list(input())
     for i in range(len(s)-1):
          if s[i] == "A" and s[i+1] == "B":
               ans += 1
     if s[0] == "B":
          b += 1
          if s[-1] == "A":
               ab += 1
     if s[-1] == "A":
          a += 1

a -= ab
b -= ab

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

Submission status: Accepted

Solution code:
N=int(input())
cntAB=0
llA=0
flB=0
flag=True
for i in range(N):
  s=input()
  cntAB+=s.count('AB')
  if s[-1]=='A': llA+=1
  if s[0]=='B': flB+=1
  if (s[-1]=='A') ^ (s[0]=='B'): flag=False

if flag: cntAB+=max(llA-1,0)
else: cntAB+=min(llA,flB)

print(cntAB)

Submission status: Accepted

Solution code:
n=int(input())
cnt_a=0
cnt_b=0
cnt_ab=0
cnt_bxa=0
for i in range(n):
  s=input()
  if s[0]=='B' and s[-1]!='A':
    cnt_b+=1
  if s[-1]=='A' and s[0]!='B':
    cnt_a+=1
  if s[0]=='B' and s[-1]=='A':
    cnt_bxa+=1
  for i in range(len(s)-1):
    if s[i:i+2]=='AB':
      cnt_ab+=1
ans=cnt_ab
if cnt_a==0 and cnt_b==0 and cnt_bxa==0:
  print(ans)
elif cnt_a==0 and cnt_b==0 and cnt_bxa!=0:
  print(ans+cnt_bxa-1)
elif cnt_a==0 and cnt_b!=0 and cnt_bxa==0:
  print(ans)
elif cnt_a!=0 and cnt_b==0 and cnt_bxa==0:
  print(ans)
elif cnt_a==0 and cnt_b!=0 and cnt_bxa!=0:
  print(ans+cnt_bxa)
elif cnt_a!=0 and cnt_b==0 and cnt_bxa!=0:
  print(ans+cnt_bxa)
elif cnt_a!=0 and cnt_b!=0 and cnt_bxa==0:
  print(ans+min(cnt_a,cnt_b))
else:
  print(ans+min(cnt_a,cnt_b)+cnt_bxa)

Submission status: Accepted

Solution code:
from sys import stdin
# import numpy as np
# import math
# import fractions
# import sys
# sys.setrecursionlimit(100000)
# N = int(stdin.readline().rstrip().split()[0])
# A = [int(x) for x in stdin.readline().rstrip().split()]
# N, X = [int(x) for x in stdin.readline().rstrip().split()]
# S = stdin.readline().rstrip().split()[0]

N = int(stdin.readline().rstrip().split()[0])

_A = 0
AB = 0
B_ = 0
B_A = 0
for _ in range(N):
  s = stdin.readline().rstrip().split()[0]
  AB += s.count("AB")
  a=0
  b=0
  if s[0] == "B":
    b = 1
  if s[-1] == "A":
    a = 1
  if a == 1 and b == 1:
    B_A += 1
  _A += a
  B_ += b

if _A == B_ == B_A == 0:
  print(AB)
elif _A == B_ == B_A:
  print(max(0, AB+B_A-1))
else:
  _AB_ = min(_A, B_)
  print(AB+_AB_)

Submission status: Accepted

Solution code:
N = int(input())
x, a, b, c = 0, 0, 0, 0
for i in range(N):
	s = input()
	x += s.count('AB')
	if s[-1] == 'A' and s[0] == 'B':
		c += 1
	elif s[-1] == 'A':
		a += 1
	elif s[0] == 'B':
		b += 1
if a == 0 and b == 0:
	x += max(c - 1, 0)
else:
	x += min(a, b) + c
print(x)

Submission status: Accepted

Solution code:
n = int(input())
strings = []
for _ in range(n):
    strings.append(input())

end_a = 0
start_b = 0
end_a_start_b = 0
for s in strings:
    if s[0] == 'B':
        start_b += 1
    if s[-1] == 'A':
        end_a += 1
    if s[0] == 'B' and s[-1] == 'A':
        end_a_start_b += 1

if end_a_start_b == 0:
    ans = min(end_a, start_b)
else:
    ans = end_a_start_b - 1
    ans += int(end_a - end_a_start_b > 0) + int(start_b - end_a_start_b > 0)
    ans += max(min(end_a - end_a_start_b - 1, start_b - end_a_start_b - 1), 0)


for s in strings:
    ans += s.count('AB')

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
s_list = [input() for _ in range(N)]
ans = 0
ans_list = [0, 0, 0]
for s in s_list:
  ans += s.count('AB')
  if s[0] == 'B' and s[-1] == 'A':
    ans_list[0] += 1
  elif s[0] == 'B':
    ans_list[1] += 1
  elif s[-1] == 'A':
    ans_list[2] += 1

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

Submission status: Accepted

Solution code:
import sys, math, collections, heapq, itertools
F = sys.stdin
def single_input(): return F.readline().strip("\n")
def line_input(): return F.readline().strip("\n").split()
def gcd(a, b):
    a, b = max(a, b), min(a, b)
    while a % b > 0:
        a, b = b, a % b
    return b
  
def solve():
    N = int(single_input())
    ab = 0
    startB, endA, both = set(), set(), set()
    for i in range(N):
        s = str(single_input())
        for j in range(len(s) - 1):
            if s[j:j+2] == "AB": ab += 1
        if s[0] == "B" and s[-1] == "A": both |= {i}
        elif s[0] == "B": startB |= {i}
        elif s[-1] == "A": endA |= {i}

        
    ab += max(len(both) - 1, 0)
    if len(startB) == 0 and len(endA) == 0: print(ab)
    else:
        single = min(len(startB), len(endA))
        if len(both) > 0: single += 1
        ab += single
        print(ab)
    
    return 0
  
if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
n = int(input())
c    = 0
plus = 0
x, y, z = 0, 0, 0 
for _ in range(n):
    s = input()
    for i in range(0, len(s)-1):
        if s[i:i+2] == 'AB': c+=1
    
    if s[0] == 'B' and s[-1]=='A': y+=1
    elif s[0]=='B': z+=1   
    elif s[-1]=='A':x+=1

if  y == 0:
    plus = min(x, z)
else:
    plus = y-1
    plus += 1 if x > 0 else 0
    plus += 1 if z > 0 else 0
    
    lr    = min(x-1,z-1) 
    plus += lr if lr > 0 else 0 
    
print(plus+c)

Submission status: Accepted

Solution code:
n=int(input())
fir=0
sec=0
same=0
ret = 0
for i in range(n):
    s = input()
    if 'AB' in s:
        ret+=s.count('AB')
    if s[0]=='B' and s[-1]=='A':
        same+=1
    else:
        if s[0]=='B':
            fir+=1
        if s[-1]=='A':
            sec+=1
if same>0:
    ret+=same-1
    if fir>0:
        ret+=1
        fir-=1
    if sec>0:
        ret+=1
        sec-=1
print(ret+min(fir,sec))

Submission status: Accepted

Solution code:
N = int(input())
Sa = []
Sb = []
Sba = []
ans = 0
for _ in range(N):
    s = input()
    if s[0] == 'B' and s[-1] == 'A':
        Sba.append(s)
    elif s[0] == 'B':
        Sb.append(s)
    elif s[-1] == 'A':
        Sa.append(s)
    ans += s.count('AB')
lsa = len(Sa)
lsb = len(Sb)
lsba = len(Sba)
if len(Sba) >= 1:
    ans += len(Sba)-1
    if lsa:
        ans += 1
        lsa -= 1
    if lsb:
        ans += 1
        lsb -= 1
ans += min(lsa, lsb)
print(ans)

Submission status: Accepted

Solution code:
if __name__ == '__main__':
    import sys
    input = sys.stdin.readline

    n = int(input())
    top = 0
    bottom = 0
    top_and_bottom = 0
    ans = 0
    for _ in range(n):
        sentence = input().rstrip()
        ans += sentence.count("AB")
        if sentence[0] == "B":
            top += 1
            if sentence[-1] == "A":
                top_and_bottom += 1
        if sentence[-1] == "A":
            bottom += 1
    if top == 0 and bottom == 0:
        print(ans)
    elif top == top_and_bottom and top_and_bottom == bottom:
        print(ans+top-1)
    else:
        print(ans+min([top, bottom]))

Submission status: Accepted

Solution code:
N=int(input())
XA=0
BA=0
BX=0
internalAB=0
for t in range(N):
    i=input()
    headUsed=False
    footUsed=False
    for x,j in enumerate(i):
        if x==len(i)-1:break
        if j=="A" and i[x+1]=="B":
            internalAB+=1
            if x==0:headUsed=True
            if x==len(i)-2:footUsed=True
    if i[0]=="B" and not headUsed:
        if i[-1]=="A" and not footUsed:
            BA+=1
        else:BX+=1
    elif i[-1]=="A" and not footUsed:
        XA+=1
if XA or BX:
    externalAB=max(0,BA+min(XA,BX))
else:externalAB=max(0,BA-1)
ans=internalAB+externalAB
print(ans)

Submission status: Accepted

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

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

print(AB)

Submission status: Accepted

Solution code:
n = int(input())
s = []
ans = 0
a,b,c = 0,0,0
for i in range(n):
    S = input()
    ans += S.count("AB")
    if S[0] == "B" and S[len(S)-1] == "A":
        a += 1
    elif S[0] == "B":
        b += 1
    elif S[len(S)-1] == "A":
        c += 1
    s.append(S)

if a >= 1:
    if b >= 1 and c >= 1:
        ans += a-1+2+min(b-1,c-1)
    elif b >= 1 or c >= 1:
        ans += a
    else:
        ans += a-1
else:
    if b >= 1 and c >= 1:
        ans += min(b,c)
print(ans)

Submission status: Accepted

Solution code:
import sys

lines = sys.stdin.readlines()

n = int(lines[0])
lines = lines[1:]
lines = [line.strip() for line in lines]
tmp = []
for line in lines:
    x = line[0]
    x += line[-1]
    tmp.append(x)

base = 0
for line in lines:
    base += line.count('AB')

# print(base)
ab = ba = ""
astart = aend = bstart = bend = 0
for line in tmp:
    if line[0] == 'A' and line[-1] == 'B':
        ab += line
    elif line[0] == 'B' and line[-1] == 'A':
        ba += line
    elif line[-1] == 'A':
        astart += 1
    elif line[0] == 'B':
        bstart += 1


# create ans
base += ba.count('AB')
if ba != "":
    if astart > 0:
        base += 1
        astart -= 1
    if bstart > 0:
        base += 1
        bstart -= 1

# do this later
base += min(astart, bstart)
print(base)

Submission status: Accepted

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

AB = 0
lastA = 0
firstB = 0
both = 0
for s in S:
  if s[-1] == 'A' and s[0] == 'B':
    both += 1
  else:
    if s[-1] == 'A':
      lastA += 1
    if s[0] == 'B':
      firstB += 1
  for i in range(len(s)-1):
    if s[i:i+2] == 'AB':
      AB += 1
x = min(lastA, firstB)
y = abs(lastA - firstB)
if x >= both:
  print(AB + both * 2 + x - both)
else:
  print(AB + both-1 + int(lastA>0) + int(firstB>0) + max(0, x-1))

Submission status: Accepted

Solution code:
N = int(input())
flag = True
ans = 0
c_A = 0
c_B = 0
for i in range(N):
    S = input()
    for i in range(len(S)-1):
        if S[i:i+2] == 'AB':
            ans += 1
    if S[0] == 'B':
        c_B += 1
        if not(S[-1] == 'A'):
            flag = False
    if S[-1] == 'A':
        c_A += 1
        if not(S[0] == 'B'):
            flag = False
if c_B == 0 or c_A == 0:
    flag = False
print(ans + min(c_A,c_B) - flag)

Submission status: Accepted

Solution code:
N = int(input())
bx = 0
xa = 0
ba = 0
count = 0
for i in range(N):
    #print("{},{},{}: {}".format(bx, xa, ba, count))
    si = input()
    if si[0] == "B":
        if si[-1] == "A":
            ba += 1
        else:
            bx += 1
    else:
        if si[-1] == "A":
            xa += 1
    count += sum([si[i:i+2]=="AB" for i in range(len(si))])
if ba == 0:
    count += min(bx, xa)
else:
    count += (ba-1) + min(1, bx) + min(1, xa) + max(0, min(bx-1, xa-1))
print(count)

Submission status: Accepted

Solution code:
count = 0
aco = 0
bco = 0
abco = 0
l = []
n = int(input())
for i in range(n):
    s = input()
    l.append(s)
    count += s.count("AB")
    if s[0] == "B" :
        bco += 1
    if s[-1] == "A" :
        aco += 1
    if s[0] == "B" and s[-1] == "A" :
        abco += 1
if max(aco,bco) == abco and aco == bco and aco != 0:
    print(count+min(aco,bco)-1)
else :
    print(count+min(aco,bco))

Submission status: Accepted

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

def count(s):
    p = 0
    result = 0
    while 1:
        q = s.find("AB", p)
        if q < 0:
            break
        p = q + 2
        result += 1
    return result

result = 0

la = 0
sb = 0
ab = 0

for s in S:
    r = count(s)
    # print("*", s, r)
    if s[-1] == "A":
        la += 1
    if s[0] == "B":
        sb += 1
        if s[-1] == "A":
            ab += 1
    result += r

la -= ab
sb -= ab

#print(la, sb, ab)

f = 0
while 1:
    if f:
        if ab >= 1:
            f = 1
            ab -= 1
            result += 1
        elif sb >= 1:
            f = 0
            sb -= 1
            result += 1
        else:
            break
    else:
        if la >= 1:
            la -= 1
            f = 1
        elif ab >= 1:
            ab -= 1
            f = 1
        else:
            break

#result += min(la, sb, N - 1)

print(result)

Submission status: Accepted

Solution code:
n=int(input())
sum=0
a=0
b=0
ab=0
for i in range(n):
    x=input()
    m=len(x)
    if x[0]=='B' and x[m-1]=='A':
        ab+=1
    elif x[0]=='B':
        b+=1
    elif x[m-1]=='A':
        a+=1
    
    for j in range(m-1):
        if x[j]=='A' and x[j+1]=='B':
            sum+=1
    
if ab==0:
    print(sum+min(a,b))
else:
    if a==0 and b==0:
        print(sum+ab-1)
    elif a==0 or b==0:
        print(sum+ab)
    else:
        print(sum+ab+1+min(a-1,b-1))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3


def solv(n, ss):
    a = 0
    b = 0
    ba = 0
    ans = 0
    for s in ss:
        ans += s.count('AB')
        if s[-1] == 'A':
            if s[0] == 'B':
                ba += 1
            else:
                a += 1
        elif s[0] == 'B':
            b += 1
    if ba > 0:
        ans += ba - 1
        if a > 0:
            ans += 1
            a -= 1
        if b > 0:
            ans += 1
            b -= 1
    ans += min(a, b)
    return ans


if __name__ == '__main__':

    n = int(input())

    ss = []
    for _ in range(n):
        ss.append(input())

    ans = solv(n, ss)

    print(ans)

Submission status: Accepted

Solution code:
import sys


fin = sys.stdin.readline
N = int(fin())
s_list = [fin().rstrip("\n") for _ in range(N)]
num_AB_in_between = 0
s_Bhoge = 0
s_hogeA = 0
s_BA = 0
for s in s_list:
    if s[0] == "B" and s[-1] == "A":
        s_BA += 1
    elif s[0] == "B":
        s_Bhoge += 1
    elif s[-1] == "A":
        s_hogeA += 1

    for i, char in enumerate(s[:-1]):
        next_char = s[i + 1]
        if char == "A" and next_char == "B":
            num_AB_in_between += 1

# print(s_Bhoge, s_hogeA, s_BA)
if s_BA:
    num_AB_bound = s_BA - 1 + int(s_Bhoge > 0) + int(s_hogeA > 0)
    num_AB_bound += max(0, min(s_Bhoge - 1, s_hogeA - 1))
    # num_AB_bound += min(s_Bhoge - 1, s_hogeA - 1)
else:
    num_AB_bound = min(s_Bhoge, s_hogeA)
print(num_AB_in_between + num_AB_bound)

Submission status: Accepted

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

inner_count = sum(s.count('AB') for s in S)

a_ends = []
b_bgns = []
for i, s in enumerate(S):
    if s[0] == 'B':
        b_bgns.append(i)
    if s[-1] == 'A':
        a_ends.append(i)

match_flag = 0
if set(a_ends) == set(b_bgns):
    match_flag = 1
join_count = max(min(len(a_ends), len(b_bgns)) - match_flag, 0)

print(inner_count + join_count)

Submission status: Accepted

Solution code:
import sys
import random
import itertools
sys.setrecursionlimit(20000000)
#input = sys.stdin.readline
n = int(input())
s = [input() for i in range(n)]
ans = 0
for i in s:
    ans += i.count("AB")
a = 0
b = 0
ba = 0
for i in s:
    if i[0] == "B" and i[-1] == "A":
        ba += 1
    elif i[0] == "B":
        b += 1
    elif i[-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)
else:
    ans += min(a,b)
print(ans)

Submission status: Accepted

Solution code:
*D, = open(0)

count = 0
right_a = 0
left_b = 0
b_middle_a = 0
for it in D[1:]:
    s = it.strip()
    count += s.count('AB')
    if s[0]=='B' and s[-1]=='A':
        b_middle_a += 1
    elif s[0] == 'B':
        left_b += 1
    elif s[-1]=='A':
        right_a+=1
    
# calculate BxxxA
if b_middle_a > 1:
    count+= (b_middle_a-1)
    b_middle_a = 1


for i in range(b_middle_a):
    if left_b >0:
        left_b-=1
        count +=1
    if right_a >0:
        right_a -= 1
        count +=1

# calculate rest
count += min(right_a, left_b)
print(count)

Submission status: Accepted

Solution code:
N = int(input())
a_count =0
b_count =0
ab_count =0
ab_alt =0
flag =0
for i in range(N):
    test = str(input())
    if test[0] == "B":
        b_count +=1
        flag =1
    if test[-1] == "A":
        a_count += 1
        if flag == 1:
            flag =0
            ab_alt +=1
    ab_count += test.count("AB")
if ab_alt != 0:
    if ab_alt == b_count:
        if ab_alt == a_count:
            a_count += -1
print(ab_count+min(a_count,b_count))

Submission status: Accepted

Solution code:
N = int(input())
cnt = 0
SB = 0
EA = 0
SBEA = 0

for i in range(N):
    s = input()
    cnt += s.count("AB")
    if s.startswith("B"):
        if s.endswith("A"):
            SBEA += 1
        else:
            SB += 1
    elif s.endswith("A"):
        EA += 1

if SBEA > 0:
    cnt += SBEA - 1
    if SB > 0:
        cnt += 1
        SB -= 1
    if EA > 0:
        cnt += 1
        EA -= 1

cnt += min(SB,EA)

print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
ab = 0
frontb = 0
backa = 0
count = 0
ryou = 0
for i in range(n):
    s = input()
    for j in range(len(s)-1):
        if s[j] == 'A' and s[j+1] == 'B':
            count += 1
    if s[0] == 'B' and s[-1] == 'A':ryou += 1
    if s[0] == 'B':frontb += 1
    if s[-1] == 'A':backa += 1
if frontb == 0 and backa == 0:
    pass
elif frontb + backa == ryou*2:
    count += backa-1
else:
    count += min(backa,frontb)
print(count)

Submission status: Accepted

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

begin_b = [False for _ in range(N)]
end_a = [False for _ in range(N)]
cnt = 0
for i, s in enumerate(S):
    for j in range(len(s)-1):
        if s[j:j+2] == 'AB':
            cnt += 1
        if s[0] == 'B':
            begin_b[i] = True
        if s[-1] == 'A':
            end_a[i] = True

cnt_ba = 0
cnt_b = 0
cnt_a = 0
for i in range(N):
    if begin_b[i] and end_a[i]:
        cnt_ba += 1
    elif begin_b[i]:
        cnt_b += 1
    elif end_a[i]:
        cnt_a += 1

if cnt_ba > 0:
    res_a = 0
    res_b = 0
    if cnt_a > 0:
        res_a = 1
        cnt_a -= 1
    if cnt_b > 0:
        res_b = 1
        cnt_b -= 1
    ans = cnt + (cnt_ba-1) + res_a + res_b + min(cnt_a, cnt_b)
else:
    ans = cnt + min(cnt_a, cnt_b)
print(ans)

Submission status: Accepted

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

answer=0
a=0
b=0
q=1
que=1
for t in s:
    for i in range(0,len(t)-1):
        if t[i]=="A" and t[i+1]=="B":
            answer+=1
    if t[0]=="B":
        b+=1
        que=0
    if t[-1]=="A":
        a+=1
        que=0
    if (t[0]=="B" and t[-1]!="A") or (t[0]!="B" and t[-1]=="A"):
        q=0
if que==1:
    q=0
if a>b:
    print(answer+b-q)
else:
    print(answer+a-q)

Submission status: Accepted

Solution code:
N = int(input())

AB_count = 0
A_end = 0
B_start = 0
B_start_and_A_end = 0
for i in range(N):
    string = input()
    AB_count += string.count("AB")
    
    if string[0] == "B":
        B_start += 1
    if string[-1] == "A":
        A_end += 1
    if string[0] == "B" and string[-1] == "A":
        B_start_and_A_end += 1
    
new_AB = min(A_end,B_start)
if B_start_and_A_end == A_end and B_start_and_A_end == B_start and B_start_and_A_end != 0:
    new_AB -= 1

print(AB_count+new_AB)

Submission status: Accepted

Solution code:
N = int(input())

a_count = 0
b_count = 0
ab_count = 0
ans = 0

for i in range(N):
    S = input()
    head = S[0]
    tail = S[-1]
    if head == 'B' and tail == 'A':
        ab_count += 1
    elif head == 'B':
        b_count += 1
    elif tail == 'A':
        a_count += 1

    index = -1
    while True:
        index = S.find("AB", index + 1)
        if index == -1:
            break
        ans+= 1

if ab_count == 0:
    print(ans + min(a_count, b_count))
else:
    if a_count == 0 and b_count == 0:
        print(ans + ab_count - 1)
    elif a_count == 0 or b_count == 0:
        print(ans + ab_count)
    else:
        print(ans + ab_count + 1 + min(a_count, b_count) - 1)

Submission status: Accepted

Solution code:
N = int(input())
s = list(input()for i in range(N))
ans = 0
A,B = 0,0
AB = 0
for i in s:
    for j in range(len(i)-1):
        if i[j:j+2] == "AB":
            ans += 1
    if i[0] == "B" and i[-1] == "A":
        AB += 1
    elif i[0] == "B":
        B += 1
    elif i[-1] == "A":
        A += 1
ans +=AB+min(A,B)
if A==0 and B==0 and AB > 0:
    ans -= 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
counter = 0

a = 0 #うしろがA
b = 0 #先頭がB
c = 0
for i in range(n):
    s = list(input())
    for k in range(len(s)-1):
        if s[k] == "A" and s[k+1] == "B":
            counter += 1
    if s[0] == "B" and s[-1] == "A":
        c += 1
    else:
        if s[-1] == "A":
            a += 1
        if s[0] == "B":
            b += 1

if c != 0:
    if a != 0 or b != 0:
        print(counter + c-1 + min(a+1,b+1))
    else:
        print(counter + c-1)
else:
    print(counter + min(a,b))

Submission status: Accepted

Solution code:
n=int(input())
s=[input() for i in range(n)]
cnt1=0
cnt2=0
cnt3=0
cnt4=0
for si in s:
    if si[0]=='B' and si[-1]=='A':
        cnt1+=1
    elif si[0]=='B':
        cnt2+=1
    elif si[-1]=='A':
        cnt3+=1
    for i in range(len(si)-1):
        if si[i]=='A' and si[i+1]=='B':
            cnt4+=1
if cnt2>=1:
    if cnt3>=1:
        print(cnt4+cnt1+min(cnt2, cnt3))
    else:
        print(cnt4+cnt1)
else:
    if cnt3>=1:
        print(cnt4+cnt1)
    elif cnt1>1:
        print(cnt4-1+cnt1)
    else:
        print(cnt4)

Submission status: Accepted

Solution code:
n = int(input())
c = [0, 0, 0]
ans = 0
for i in range(n):
    si = input()
    ans += si.count('AB')
    if si[0] == 'B' and si[-1] == 'A':
        c[0] += 1
    elif si[0] == 'B':
        c[1] += 1
    elif si[-1] == 'A':
        c[2] += 1
ans += max(0, c[0] - 1)
if c[0] > 0 and c[1] > 0:
    ans += 1
    c[1] -= 1
if c[0] > 0 and c[2] > 0:
    ans += 1
    c[2] -= 1
ans += max(0, min(c[1:]))
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
s = []

result = 0
ABAB = 0
A = 0
B = 0
onon = 0

amari = 0
for i in range(N):
    s.append(input())

for S in s:
    AB = S.count("AB")
    result += AB
    if S[0] == "B" and S[-1] == "A":
        ABAB += 1
    elif S[0] == "B":
        B += 1
    elif S[-1] == "A":
        A += 1

if ABAB >= 1:
    onon = onon + ABAB - 1

if A >= 1 and ABAB >= 1 :
    onon += 1
    A -= 1
if B >= 1 and ABAB >= 1 :
    onon += 1
    B -= 1

if A >= 1 and B >= 1:
    if A >= B:
        onon += B
    else:
        onon += A


print(result + onon)

Submission status: Accepted

Solution code:
n = int(input())
a = 0
b = 0
ba = 0
cnt = 0
for i in range(n):
    s = input()
    cnt += s.count('AB')
    s.replace('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:
    if a > 0 and b > 0:
        cnt += ba + 1
        a -= 1
        b -= 1
    elif a > 0:
        cnt += ba
        a -= 1
    elif b > 0:
        cnt += ba
        b -= 1
    else:
        cnt += ba - 1

cnt += min(a, b)

print(cnt)

Submission status: Accepted

Solution code:
N = int(input())

ans = 0
aEnd = 0
bStart = 0
abBoth = 0
for _ in range(N):
    s = input()
    if s[0] == "B":
        bStart += 1
    if s[-1] == "A":
        aEnd += 1
        if s[0] == "B":
            abBoth += 1

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

ans += min(aEnd, bStart)
if abBoth != 0 and abBoth == aEnd == bStart:
    ans -= 1

print(ans)

Submission status: Accepted

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

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

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

if numBA > 0:
    ans += numBA - 1
    if num_A > 0:
        ans += 1
        num_A -= 1
    if numB_ > 0:
        ans += 1
        numB_ -= 1

ans += min(num_A, numB_)

print(ans)

Submission status: Accepted

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

b = 0
a = 0
ba = 0

cnt = 0
for x in s:
    if x[0] == "B" and x[-1] == "A":
        ba+=1
    if x[0] == "B":
        b+=1
    if x[-1] == "A":
        a+=1
    cnt += x.count("AB")

cnt2 = 0
if ba==b and ba==a and ba!=0:
    cnt2 = ba-1
else:
    cnt2 = min(a,b)

print(cnt+cnt2)

Submission status: Accepted

Solution code:
n = int(input())
cnt = 0
s0b = 0
sla = 0
s0bsla = 0
for i in range(n):
    s = input()
    cnt += s.count("AB")
    if s[0] == "B" and s[-1] != "A":
        s0b += 1
    elif s[0] != "B" and s[-1] == "A":
        sla += 1
    elif s[0] == "B" and s[-1] == "A":
        s0bsla += 1
if s0bsla > 0:
    cnt += s0bsla - 1
    if sla > 0:
        cnt += 1
        sla -= 1
    if s0b > 0:
        cnt += 1
        s0b -= 1
cnt += min(s0b, sla)
print(cnt)

Submission status: Accepted

Solution code:
N = int(input())
cnt = 0
endA = 0
startB = 0
both = 0
for i in range(N):
	s = input()
	flgA = s[-1] == "A"
	flgB = s[0] == "B"
	if flgA and flgB:
		both += 1
	elif flgA:
		endA += 1
	elif flgB:
		startB += 1
	cnt += s.count("AB")

if both > 0:
	if both > 1:
		cnt += both - 1
	if endA > 0:
		cnt += 1
		endA -= 1
	if startB > 0:
		cnt += 1
		startB -= 1
cnt += min(endA, startB)
print(cnt)

Submission status: Accepted

Solution code:
# diverta 2019 Programming Contest
# https://atcoder.jp/contests/diverta2019
import sys

s2nn = lambda s: [int(c) for c in s.split(' ')]
ss2nn = lambda ss: [int(s) for s in list(ss)]
ss2nnn = lambda ss: [s2nn(s) for s in list(ss)]
i2s = lambda: sys.stdin.readline().rstrip()
i2n = lambda: int(i2s())
i2nn = lambda: s2nn(i2s())
ii2ss = lambda n: [sys.stdin.readline().rstrip() for _ in range(n)]
ii2nn = lambda n: ss2nn(ii2ss(n))
ii2nnn = lambda n: ss2nnn(ii2ss(n))

def main():
    N = i2n()
    S = ii2ss(N)
    c0b = 0
    c1a = 0
    c0b1a = 0
    c = 0
    for s in S:
        for i, t in enumerate(s[:-1]):
            if t == 'A':
                if s[i+1] == 'B':
                    c += 1
        if s[0] == 'B' and s[-1] == 'A':
            c0b1a += 1
        elif s[0] == 'B':
            c0b += 1
        elif s[-1] == 'A':
            c1a += 1
    c0b1a_min = min(c0b, c1a)
    c += c0b1a_min
    if c0b1a > 0:
        if c0b > 0 or c1a > 0:
            c += c0b1a
        else:
            c += c0b1a - 1
    print(c)

main()

Submission status: Accepted

Solution code:
n = int(input())
s = list()
count = 0
oa = 0
bo = 0
ba = 0
for i in range(0,n):
    s.append(str(input()))
    count += s[i].count("AB")
    if s[i][0] == "B":
        if s[i][-1] == "A":
            ba += 1
        else:
            bo += 1
    elif s[i][-1] == "A":
        oa += 1

if ba > 0:
    count += ba-1
    if oa > 0:
        count += 1
        oa -=1
    if bo >0:
        count += 1
        bo -=1
    count += min(oa,bo)
elif ba == 0:
    count += min(oa,bo)
print(count)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
s = []

result = 0
ABAB = 0
A = 0
B = 0
onon = 0

amari = 0
for i in range(N):
    s.append(input())

for S in s:
    AB = S.count("AB")
    result += AB
    if S[0] == "B" and S[-1] == "A":
        ABAB += 1
    elif S[0] == "B":
        B += 1
    elif S[-1] == "A":
        A += 1

if ABAB >= 1:
    onon = onon + ABAB - 1

if A >= 1 and ABAB >= 1 :
    onon += 1
    A -= 1
if B >= 1 and ABAB >= 1 :
    onon += 1
    B -= 1

if A >= 1 and B >= 1:
    if A >= B:
        onon += B
    else:
        onon += A


print(result + onon)

Submission status: Accepted

Solution code:
# coding:utf-8

import sys
from collections import deque, Counter

INF = float('inf')
MOD = 10 ** 9 + 7
dy, dx = (0, -1, 0, 1), (1, 0, -1, 0)

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 LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()


def main():
    n = II()
    S = [SI() for _ in range(n)]

    cnt = {"B_": 0, "_A": 0, "B_A": 0}
    res = 0
    for s in S:
        for i in range(len(s) - 1):
            if s[i: i + 2] == 'AB':
                res += 1

        if s[0] == 'B' and s[-1] == 'A':
            cnt["B_A"] += 1
        elif s[0] == 'B':
            cnt["B_"] += 1
        elif s[-1] == 'A':
            cnt["_A"] += 1

    # print(res, cnt)
    res += min(cnt["B_"], cnt["_A"])
    if max(cnt["B_"], cnt["_A"]) > 0:
        res += cnt["B_A"]
    else:
        res += max(0, cnt["B_A"] - 1)

    print(res)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n=int(input())
count=0
bx=0
xa=0
ba=0
for i in range(n):
    s=input()
    for j in range(0,len(s)-1):
        if s[j:j+2]=='AB':
            count=count+1
    if s[0]=='B' and s[len(s)-1]=='A':
        ba=ba+1
    if s[0]=='B' and not s[len(s)-1]=='A':
        bx=bx+1
    if not s[0]=='B' and s[len(s)-1]=='A':
        xa=xa+1
if bx==0 and xa==0:
    if ba>=2:
        count=count+ba-1
else:
    count=count+ba+min(xa,bx)
print(count)