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 = 0
ab_ = 0
a = 0
b = 0
for i in s:
  ab += i.count("AB")
  if i[0] == "B" and i[-1] == "A":
    ab_ += 1
  if i[0] == "B":
    b += 1
  if i[-1] == "A":
    a += 1
if ab_ == a and ab_ == b and not ab_ == 0:
  print(ab+ab_-1)
else:
  print(ab+min([a,b]))

Submission status: Accepted

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

for i in range(n):
    s.append(list(input()))

x = 0    

for i in range(n):
    for j in range(1,len(s[i])):
        if s[i][j-1]=="A" and s[i][j]=="B":
            x += 1

p = 0
q = 0
r = 0
for i in range(n):
    if s[i][0]=="B" and s[i][-1]!= "A":
        p += 1
    if s[i][0]!="B" and s[i][-1]=="A":
        q += 1
    if s[i][0]== "B" and s[i][-1]=="A":
        r +=1


if p==0 and q==0 and r!=0:
    print(x+r-1)
else:
    print(x+r+min(p,q))

Submission status: Accepted

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


def solve(N: int, s: "List[str]"):
    x = 0
    a = 0
    b = 0
    for i in s:
        if(i[0] == 'B' and i[-1] == 'A'):
            x += 1
        elif(i[-1] == 'A'):
            a += 1
        elif(i[0] == 'B'):
            b += 1
    
    
    ####   AC1   #####    
    # if(x == 0):
    #     ans1 = min(a,b)
    # else:
    #     ans1 = max(0,x-1)+min(a,b)
    #     if(a > 0 or b > 0):
    #         ans1 += 1
    
    #####    AC2   ####
    ans1 = max(0,x-1) + min(a,b)
    if((a > 0 or b >0) and x > 0):
        ans1 += 1
    
    ####   WA    #############
    # ans1 = max(0,x-1) + min(a,b)
    # if(x != 0):
    #     ans1 += 1 
    

    ans1 = max(0,x-1) 
    if(a == b):
        ans1 += min(a,b)
        if((a > 0 or b > 0) and x != 0):
            ans1 += 1
    else:
        if(x == 0):
            ans1 += min(a,b)
        elif(a > 0 or b > 0):
            ans1 += min(a,b)+1 

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

    print(ans1+ans2)
    
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    s = [ next(tokens) for _ in range(N) ]  # type: "List[str]"
    solve(N, s)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())

count_ab = 0
S_tail_a_head_b = 0
S_tail_a = 0
S_head_b = 0
for _ in range(N):
    s = input()
    count_ab += s.count('AB')

    if s[0] != 'B' and s[-1] != 'A':
        continue

    if s[0] == 'B' and s[-1] == 'A':
        S_tail_a_head_b += 1
    elif s[0] == 'B':
        S_head_b += 1
    elif s[-1] == 'A':
        S_tail_a += 1

if S_tail_a_head_b == 0:
    count_ab += min(S_head_b, S_tail_a)
else:
    if sum([S_tail_a, S_head_b]) > 0:
        count_ab += S_tail_a_head_b + min(S_head_b, S_tail_a)
    else:
        count_ab += S_tail_a_head_b - 1

print(count_ab)

Submission status: Accepted

Solution code:
from sys import stdin
import math
import itertools


def makeIntMatrix(lines):
    intMatrix = []
    for a in makeStringMatrix(lines):
        intMatrix.append([int(b) for b in a])
    return intMatrix
 
 
def makeStringMatrix(lines):
    stringMatrix = [line.rstrip() for line in lines]
    return stringMatrix
 
 
def makeInt(line):
    return int(line.rstrip())
 
 
def makeMultiInteger(line):
    return [int(x) for x in line.rstrip().split()]


def solve(input_string):
    N = makeInt(input_string[0])
    S = makeStringMatrix(input_string[1:])
    #print(S)
    C_S_has_ab = []
    for s_index, s in enumerate(S):
        C_S_has_ab.append(0)
        for i in range(len(s)-1):
            if s[i] + s[i+1] == 'AB':
                C_S_has_ab[s_index] += 1
    #print(C_S_has_ab)
    _sum = 0
    _sum += sum(C_S_has_ab) 
    c_head_has_b = 0
    c_tail_has_a = 0
    c_head_tail_has_a_and_b = 0
    for s in S:
        """
        if s[0] == 'B':
            c_head_has_b += 1
        if s[-1] == 'A':
            c_tail_has_a += 1
        if s[0] == 'B' and s[-1] == 'A':
            c_head_tail_has_a_and_b += 1
        """
        if(s[0] == 'B' and s[-1] == 'A'):
            c_head_tail_has_a_and_b += 1
        elif(s[-1] == 'A'):
            c_tail_has_a += 1
        elif(s[0] == 'B'):
            c_head_has_b += 1
    #print(c_head_has_b, c_tail_has_a, c_head_tail_has_a_and_b)
    if c_head_tail_has_a_and_b > 0:
        count_combi_a_b = max(0, c_head_tail_has_a_and_b-1) + min(c_head_has_b, c_tail_has_a)
        if c_head_has_b > 0 or c_tail_has_a > 0:
            count_combi_a_b += 1
    else:
        count_combi_a_b = min(c_head_has_b, c_tail_has_a)
    _sum += count_combi_a_b
    #print(_sum)
    return _sum


def main():
    input_lines = stdin.readlines()
    answer = solve(input_lines)
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

N = int(input())
string_list = [input() for i in range(N)]

counter = 0
#左端がb and 右端がa の数
ab = 0
#ab以外で右端がaの数
a = 0
#ab以外で左端がbの数
b = 0

for s in string_list:
    #ここで一つの文字列内にABが複数ある場合が抜けてた
    if 'AB' in s:
        counter += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        ab += 1
    elif s[0] == 'B':
        b += 1
    elif s[-1] == 'A':
        a += 1

c = min(a,b)
d = max(a,b)
if d == 0 and ab > 0:
    counter += ab - 1
else:
    counter += c + ab
'''
if ab == 0:
    counter += min(a,b)
elif a + b == 0:
    counter += ab - 1
else:
    counter += min(a,b) + ab
'''
print(counter)

Submission status: Accepted

Solution code:
N=int(input())
a=0
b=0
B=0
A=0
count1=0
count2=0
for i in range(N):
    S=input()
    a+=S.count("AB")
    if S[0]=="B"and S[len(S)-1]=="A":
        count1+=1
        if count1==1:
            A+=1
            B+=1
        else:
            b+=1
    elif S[0]=="B":
        B+=1
        count2+=1
    elif S[len(S)-1]=="A":
        A+=1
        count2+=1
if count1>1 and count2==0:
    b=b-1
C=min(A+b,B+b)
print(a+C)

Submission status: Accepted

Solution code:
N = int(input())
A = 0
B = 0
AB = 0
ans = 0

S = list()

for _ in range(N):
    S.append(input())

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

if AB == 0:
    ans += min(A, B)
else:
    if A + B != 0:
        ans += AB + min(A, B)
    else:
        ans += AB - 1

print(ans)

Submission status: Accepted

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


def solve(N: int, s: "List[str]"):
    x = 0
    a = 0
    b = 0
    for i in s:
        if(i[0] == 'B' and i[-1] == 'A'):
            x += 1
        elif(i[-1] == 'A'):
            a += 1
        elif(i[0] == 'B'):
            b += 1
    
    
    ####   AC   #####    
    # if(x == 0):
    #     ans1 = min(a,b)
    # else:
    #     ans1 = max(0,x-1)+min(a,b)
    #     if(a > 0 or b > 0):
    #         ans1 += 1
    ans1 = max(0,x-1) + min(a,b)
    if((a > 0 or b >0) and x > 0):
        ans1 += 1
    # if(a == b):
    #     if(x != 0 and a > 0):
    #         ans1 += 1
    # else:
    #     if(a > 0 or b > 0):
    #         ans1 += 1
             

    
    # ans1 = max(0,x-1) 
    # if(a == b):
    #     ans1 += min(a,b)
    # else:
    #     if(x == 0):
    #         ans1 += min(a,b)
    #     else:
    #         ans1 += min(a,b)+1 
    

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

    print(ans1+ans2)
    
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    s = [ next(tokens) for _ in range(N) ]  # type: "List[str]"
    solve(N, s)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

N=INT()
S=['']*N
for i in range(N):
    S[i]=input()

enda=0
startb=0
both=0
cntab=0
for i in range(N):
    if S[i].startswith('B') and S[i].endswith('A'):
        both+=1
    elif S[i].startswith('B'):
        startb+=1
    elif S[i].endswith('A'):
        enda+=1
    cntab+=S[i].count('AB')

cntab+=max(both-1, 0)
mnab=min(enda, startb)
cntab+=mnab
if max(enda, startb)!=0 and both!=0:
    cntab+=1
print(cntab)

Submission status: Accepted

Solution code:
N=int(input())
s=list(input() for _ in range(N))
ans=0
count=0
a_count=0
b_count=0
ab_count=0
for i in s:
    ans+=i.count('AB')
    if i[0]=='B'and i[-1]=='A':
        ab_count+=1
    elif i[0]=='B':
        b_count+=1
    elif i[-1]=='A':
        a_count+=1
print(ans+min(a_count,b_count)+ab_count if a_count+b_count!=0 else ans+max(ab_count-1,0))

Submission status: Accepted

Solution code:
N = int(input())

AB = 0
Bxxx = 0
xxxA = 0
BxxA = 0
for i in range(N):
    s = input()
    AB += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        BxxA += 1
    elif s[0] == 'B':
        Bxxx += 1
    elif s[-1] == 'A':
        xxxA += 1

if Bxxx == 0 and xxxA == 0:
    print(AB + max(BxxA - 1, 0))
else:
    print(AB + min(Bxxx, xxxA) + BxxA)

Submission status: Accepted

Solution code:
n=int(input())
a=0;b=0;ab=0;res=0
for i in range(n):
    s=input()
    res+=s.count("AB")
    if s[0]=="B":
        if s[-1]=="A":
            ab+=1
        else:
            b+=1
    elif s[-1]=="A":
        a+=1
if ab>0:
    res+=ab-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())
ans=0
flagA=[]
flagB=[]
fla=0
flb=0
for x in range(n):
    s = input()
    if 'AB' in s:
        ans += s.count('AB')
    if s[-1]=='A':
        flagA.append(x)
        fla+=1
    if s[0]=='B':
        flagB.append(x)
        flb+=1
if flagA==flagB and len(flagA)!=0:
    ans-=1
ans+=min(fla,flb)
print(ans)

Submission status: Accepted

Solution code:
n= int( input() )
ss= [ input() for i in range(n) ]
 
ea=0
sb=0
easb=0
cnt= 0
for s in ss:
    cnt+= s.count("AB")
    la= s[-1]=="A"
    lb= s[ 0]=="B"
    if la: ea+=1
    if lb: sb+=1
    if la and lb: easb+=1
#
tot= cnt+min(ea,sb)
if ea==sb==easb and easb>0: tot-=1
print( tot )

Submission status: Accepted

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

ans = 0
head_b = 0
tail_a = 0
headAndTail = 0

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

    if s.startswith('B') and s.endswith('A'):
       headAndTail += 1
    elif s.startswith('B'):
        head_b += 1
    elif s.endswith('A'):
        tail_a += 1

ans += min([head_b, tail_a])

if head_b == 0 and tail_a == 0:
    ans += max([0,headAndTail-1])
else:
    ans += headAndTail

print(ans)

Submission status: Accepted

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

cnt = 0
xa = bx = ba = 0
for i in range(n):
  s = li[i]
  cnt += s.count("AB")
  if s.find("B")==0 and s.rfind("A")==len(s)-1:
    ba += 1
  elif s.find("B") == 0:
    bx += 1
  elif s.rfind("A") == len(s)-1:
    xa += 1

if xa == 0 and bx == 0 and ba != 0:
  print("{}".format(cnt+ba-1))
elif xa == 0 and bx == 0 and ba == 0:
  print("{}".format(cnt))
elif xa == 0 or bx == 0:
  print("{}".format(cnt+ba))
else:
  print("{}".format(cnt+ba+1+min([xa-1,bx-1])))

Submission status: Accepted

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


def solve(N: int, s: "List[str]"):
    x = 0
    a = 0
    b = 0
    for i in s:
        if(i[0] == 'B' and i[-1] == 'A'):
            x += 1
        elif(i[-1] == 'A'):
            a += 1
        elif(i[0] == 'B'):
            b += 1

    # ans1 = max(0,x-1) + (min(a,b) if a==b else min(a,b)+1)    
    
    if(x == 0):
        ans1 = min(a,b)
    else:
        ans1 = max(0,x-1)+min(a,b)
        if(a > 0 or b > 0):
            ans1 += 1

    
    # ans1 = max(0,x-1) 
    # if(a == b):
    #     ans1 += min(a,b)
    # else:
    #     if(x == 0):
    #         ans1 += min(a,b)
    #     else:
    #         ans1 += min(a,b)+1 
    

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

    print(ans1+ans2)
    
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    s = [ next(tokens) for _ in range(N) ]  # type: "List[str]"
    solve(N, s)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
s = []
for i in range(n):
  s.append(list(input()))
c1 = 0
c2 = 0
c3 = 0
for i in range(n):
  if s[i][0] == 'B' and s[i][-1] == 'A':
    c1 += 1
  elif s[i][0] == 'B':
    c2 += 1
  elif s[i][-1] == 'A':
    c3 += 1
if c3 == 0 and c2 == 0 and c1 > 0:
  c1 -= 1
min = min(c1+c2, c1+c3)
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
print(ans+min)

Submission status: Accepted

Solution code:
N = int(input())

Bxxx = 0
xxxA = 0
BxxA = 0
xABx = 0
for i in range(N):
    s = input()
    xABx += s.count("AB")
    if (s[0] == "B") and (s[-1] == "A"):
        BxxA += 1
    else:
        if s[0] == "B":
            Bxxx += 1
        if s[-1] == "A":
            xxxA += 1
#print("Bxxx={},xxxA={},BxxA={},xABx={}".format(Bxxx,xxxA,BxxA,xABx))

if BxxA == 0:
    print(xABx + min(Bxxx, xxxA))
elif Bxxx == xxxA == 0:
    print(xABx + BxxA - 1)
else:
    #set3 = min(BxxA, Bxxx, xxxA)
    #print(xABx + set3 * 2 + BxxA - set3 + min(Bxxx, xxxA) - set3)
    print(xABx + BxxA + min(Bxxx, xxxA))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

N = int(input())

count_ab = 0
count_fb = 0
count_ea = 0
count_fbea = 0
for i in range(N):
    s = input()
    count_ab += s.count("AB")
    if s[0] + s[-2] == "BA":
        count_fbea += 1
    elif s[0] == "B":
        count_fb += 1
    elif s[-2] == "A":
        count_ea += 1

ans = count_ab
if count_fbea > 0:
    ans += count_fbea - 1
    if count_fb > 0:
        count_fb -= 1
        ans += 1
    if count_ea > 0:
        count_ea -= 1
        ans += 1
ans += min(count_fb, count_ea)
print(ans)

Submission status: Accepted

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

base_ab=0
last_a=0
first_b=0
all_ba=0
for s in string:
    base_ab+=s.count("AB")
    if s[-1]=="A":
        last_a+=1
    if s[0]=="B":
        first_b+=1
    if s[0]=="B" and s[-1]=="A":
        all_ba+=1
if last_a-all_ba==0 and first_b-all_ba==0 and all_ba>0:
    print(base_ab+min(last_a,first_b)-1)
else:    
    print(base_ab+min(last_a,first_b))

Submission status: Accepted

Solution code:
N = int(input())
 
a = 0
b = 0
c = 0
count = 0
for i in range(N):
    s = input()
    count += len([1 for j in range(len(s)) if s[j:j+2] == "AB"])
    if s[-1] == "A":
        a += 1
    if s[0] == "B":
        b += 1
    if s[0] == "B" and s[-1] == "A":
        c += 1

if a == b and b == c and c != 0:
    print(count + c - 1)
else:
    print(count + min([a, b, N-1]))

Submission status: Accepted

Solution code:
N = int(input())

count_ab = 0
count_fb = 0
count_ea = 0
count_fbea = 0
for i in range(N):
    s = input()
    count_ab += s.count("AB")
    if s[0] + s[-1] == "BA":
        count_fbea += 1
    elif s[0] == "B":
        count_fb += 1
    elif s[-1] == "A":
        count_ea += 1

ans = count_ab
if count_fbea > 0:
    ans += count_fbea - 1
    if count_fb > 0:
        count_fb -= 1
        ans += 1
    if count_ea > 0:
        count_ea -= 1
        ans += 1
ans += min(count_fb, count_ea)
print(ans)

Submission status: Accepted

Solution code:
'''
C - AB Substrings
'''

str_list = []
ab_num = 0
c1 = 0
c2 = 0
c3 = 0
for i in range(int(input())):
    str_list.append(input())
    ab_num += str_list[-1].count('AB')
    if str_list[-1].endswith('A') and str_list[-1].startswith('B'):
        c1 += 1
    elif str_list[-1].startswith('B'):
        c2 += 1
    elif str_list[-1].endswith('A'):
        c3 += 1

if c1 == 0:
    print(ab_num + min(c2, c3))
elif c2 + c3 == 0:
    print(ab_num + c1 - 1)
else:
    print(ab_num + c1 + min(c2, c3))

Submission status: Accepted

Solution code:
N = int(input())

Bxxx = 0
xxxA = 0
BxxA = 0
AB = 0
for i in range(N):
    s = input()
    AB += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        BxxA += 1
    elif s[0] == 'B':
        Bxxx += 1
    elif s[-1] == 'A':
        xxxA += 1

if BxxA == 0:
    print(AB + min(Bxxx, xxxA))
elif Bxxx + xxxA == 0:
    print(AB + BxxA - 1)
else:
    print(AB + min(Bxxx, xxxA) + BxxA)

Submission status: Accepted

Solution code:
N = int(input())

count_ab = 0
count_fb = 0
count_ea = 0
count_fbea = 0
for i in range(N):
    s = input()
    count_ab += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        count_fbea += 1
    elif s[0] == "B":
        count_fb += 1
    elif s[-1] == "A":
        count_ea += 1

ans = count_ab
if count_fbea > 0:
    ans += count_fbea - 1
    if count_fb > 0:
        count_fb -= 1
        ans += 1
    if count_ea > 0:
        count_ea -= 1
        ans += 1
ans += min(count_fb, count_ea)
print(ans)

Submission status: Accepted

Solution code:
import numpy as np
    
n = int(input())
S = np.asarray([])
St = np.zeros(4) # None,B,A,BA
count = 0

for i in range(n):
    S=np.append(S,input())
    tmp = 0
    count += S[i].count("AB")
    if S[i][0] == "B":
        tmp += 1
    if S[i][-1] == "A":
        tmp += 2
    St[tmp]+=1

if (St[1] == 0)&(St[3]>0):
    St[1]+=1
    St[3]-=1

if (St[2] == 0)&(St[3]>0):
    St[2]+=1
    St[3]-=1

print(int(count+min(St[1],St[2])+St[3]))

Submission status: Accepted

Solution code:
N = int(input())

count_ab = 0
count_fb = 0
count_ea = 0
count_fbea = 0
for i in range(N):
    s = input()
    count_ab += s.count("AB")
    if s[0] == "B" and s[len(s)-1] == "A":
        count_fbea += 1
    elif s[0] == "B":
        count_fb += 1
    elif s[len(s)-1] == "A":
        count_ea += 1

ans = count_ab
if count_fbea > 0:
    ans += count_fbea - 1
    if count_fb > 0:
        count_fb -= 1
        ans += 1
    if count_ea > 0:
        count_ea -= 1
        ans += 1
ans += min(count_fb, count_ea)
print(ans)

Submission status: Accepted

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

cnt = 0
b = 0
a = 0
ab = 0
for x in S:
    cnt += x.count('AB')
    if x[0] == 'B' and x[-1] == 'A':
        ab += 1
        continue
    if x[0] == 'B':
        b += 1
    if x[-1] == 'A':
        a += 1
    

if (a>0 and b>0) or ab>=2:
    if a==0:
        a = 1
        ab -= 1
    if b==0:
        b = 1
        ab -= 1
    cnt += min(a,b) + ab

print(cnt)

Submission status: Accepted

Solution code:
str_dict = [0, 0, 0] 
val1 = 0
for i in range(int(input())):
  line = input()
  val1 += line.count('AB')
  if line[0] == 'B' and line[-1] == 'A':
    str_dict[2] += 1
  elif line[0] == 'B':
    str_dict[0] += 1
  elif line[-1] == 'A':
    str_dict[1] += 1
if str_dict[2] == 0:
  print(val1+min(str_dict[0], str_dict[1]))
else:
  if str_dict[0]+str_dict[1] > 0:
    print(val1+str_dict[2]+min(str_dict[0], str_dict[1]))
  else:
    print(val1+str_dict[2]-1)

Submission status: Accepted

Solution code:
N = int(input())
ba = b = a = ans = 0
for i 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 += min(a, b)
else:
    if a + b > 0:
        ans += ba + min(a, b)
    else:
        ans += ba - 1

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
cntA, cntB, cntBoth, ans = 0, 0, 0, 0

for i in range(N):
    s = input()
    L = len(s)
    if s[0] == 'B':
        cntB += 1
    if s[L-1] == 'A':
        cntA += 1
    if s[0] == 'B' and s[L-1] == 'A':
        cntBoth += 1
    for i in range(L-1):
        if s[i:i+2] == 'AB':
            ans += 1
# print(ans, cntA, cntB, cntBoth)
ans += min(cntA, cntB)
if cntA == cntB and cntA == cntBoth and cntBoth > 0:
    ans -= 1
print(ans)

Submission status: Accepted

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

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

cnt = 0
both_ab = 0
last_a = 0
initial_b = 0
for i in range(N):
    if s[i].count('AB') > 0:
        cnt += s[i].count('AB')

    if s[i][-1] == 'A' and s[i][0] == 'B':
        both_ab += 1
    elif s[i][-1] == 'A':
        last_a += 1
    elif s[i][0] == 'B':
        initial_b += 1


def calc(cnt, both_ab, last_a, initial_b):
    if both_ab == 0:
        min_a_b = min(initial_b, last_a)
        cnt += min_a_b
        return cnt

    if min(both_ab, last_a) > min(both_ab, initial_b):
        cnt += min(both_ab, initial_b)
        both_ab -= min(both_ab, initial_b)
    else:
        cnt += min(both_ab, last_a)
        both_ab -= min(both_ab, last_a)

    if last_a == 0 and initial_b == 0:
        return cnt + both_ab - 1

    min_a_b = min(initial_b, last_a)
    cnt += min_a_b

    return both_ab + cnt


ans = calc(cnt, both_ab, last_a, initial_b)
print(ans)

Submission status: Accepted

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

a = [0] * N
b = [0] * N

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

special = 0

for i in range(N):
    if a[i] == 1 and b[i] == 1:
        special += 1
        a[i] = 0
        b[i] = 0


counta = a.count(1)
countb = b.count(1)



if counta == 0 and countb == 0 and special > 0:
    ans += special - 1
else:
    ans += min(counta + special, countb + special)


print(ans)

Submission status: Accepted

Solution code:
#coding: utf-8
N = int(input())
ans = 0
l_B = 0
r_A = 0
lbra = 0
for _ in range(N):
	tmp = input()
	ans += tmp.count("AB")
	if tmp[0] == "B":
		if tmp[-1] == "A":
			lbra += 1
		else:
			l_B += 1
	elif tmp[-1] == "A":
		r_A += 1
        
if lbra == 0:
    ans += min(l_B, r_A)
else:
    if l_B + r_A > 0:
        ans += lbra + min(l_B, r_A)
    else:
        ans += lbra - 1
print(ans)

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

x, y, z = 0, 0, 0  # xは~A、yはB~、zはB~Aの個数
for k in range(N):
	if s[k][0] == "B" and s[k][-1] =="A":
		z += 1
	elif s[k][0] == "B":
		y += 1
	elif s[k][-1] == "A":
		x += 1

if x >= 1 and y >= 1:
	ans += z + min(x, y)
elif x >= 1 or y >= 1:
	ans += z
else:
	ans += max(0, z - 1)

print(ans)

Submission status: Accepted

Solution code:
n,*s=open(0)
a=b=c=d=0
for t in s:
    if t[-2]=='A'and t[0]=='B':
        d+=1
    elif t[-2]=='A':
        a+=1
    elif t[0]=='B':
        b+=1
    c+=t.count('AB')
if all(i==0for i in(a,b)):
    print(c+max(0,d-1))
    exit()
elif a==b:
    print(a+c+d)
    exit()
ans=min(a,b)+c
dif=abs(a-b)
ans+=min(dif,d)
d-=min(dif,d)
print(ans+d)

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for _ in range(N)]
Alist = [word for word in S if word[-1] == 'A']
Blist = [word for word in S if word[0] == 'B']
ABlist = [word for word in S if word[0] == 'B' and word[-1] == 'A']
Slist = [word.count('AB') for word in S]
C = min(len(Alist),len(Blist))
if len(Alist) == 0 and len(Blist) == 0:
    print(sum(Slist))
elif len(ABlist) == len(Alist) and len(ABlist) == len(Blist):
    print(sum(Slist)+len(ABlist)-1)
else:
    print(sum(Slist)+min(C,N-1))

Submission status: Accepted

Solution code:
n = int(input())
s_list = [input() for _ in range(n)]
 
ab_count = 0
b_start = 0
a_end = 0
concat_max = 0
 
for s in s_list:
    is_b = s[0] == 'B'
    is_a = s[-1] == 'A'
    if is_b:
        b_start = b_start + 1
    if is_a:
        a_end = a_end + 1
    if is_a or is_b:
        concat_max = concat_max + 1
    ab_count = ab_count + s.count('AB')
 
print(ab_count + max(min(min(a_end, b_start), concat_max - 1), 0))

Submission status: Accepted

Solution code:
N = int(input())

ba = 0
_a = 0
b_ = 0
ans = 0
for _ in range(N):
    s = input()
    ans += s.count('AB')
    if s[-1] == 'A' and s[0] == 'B':
        ba += 1
    elif s[-1] == 'A':
        _a += 1
    elif s[0] == 'B':
        b_ += 1

if _a == b_ == 0 and ba > 0:
    ans += ba - 1
else:
    ans += min(ba+_a, ba+b_)

print(ans)

Submission status: Accepted

Solution code:
n=int(input())
s=[]
ctr=0
ctr_a=0
ctr_b=0
ctr_ab=0
for i in range(n):
    s.append(str(input()))
    if "AB" in s[i]:
        ctr+=s[i].count("AB")
    if s[i][-1]=="A" and s[i][0]!="B":
        ctr_a+=1
    if s[i][0]=="B" and s[i][-1]!="A":
        ctr_b+=1
    if s[i][-1]=="A" and s[i][0]=="B":
        ctr_ab+=1
if ctr_ab==0:
    print(ctr+min(ctr_a,ctr_b))
else:
    if ctr_a+ctr_b>0:
        print(ctr+min(ctr_a,ctr_b)+ctr_ab)
    else:
        print(ctr+ctr_ab-1)

Submission status: Accepted

Solution code:
n = int(input())
ab = 0
bx = 0
xa = 0
bxa = 0

for ln in range(n):
    line = input().rstrip()
    ab += line.count("AB")
    first , last = line[0], line[-1]
    if (first, last) == ('B', 'A'):
        bxa += 1
    elif first == 'B':
        bx += 1
    elif last == 'A':
        xa += 1

if bx + xa == 0:
    bxa = max(0, bxa - 1)

print(ab + bxa + min(bx, xa))

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    word = []
    cnt = 0
    cnt_h = 0
    cnt_t = 0
    cnt_ht = 0
    total = 0
    for i in range(N):
        search = input()
        cnt += search.count('AB')
        if search[0] != 'B' and search[-1] !='A':
            continue
        elif search[0] =='B' and search[-1] =='A':
            cnt_ht +=1
        elif search[0] =='B':
            cnt_h +=1
        else:
            cnt_t +=1
    if cnt_ht ==0:
        print(cnt + min(cnt_h,cnt_t))
    elif cnt_t + cnt_h ==0:
        print(cnt + cnt_ht -1)
    else:
        print(cnt + min(cnt_h,cnt_t)+ cnt_ht)
if __name__ == '__main__':
    main()

Submission status: Accepted

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

cnt = 0
BA = 0 # 'B~A'
lA = 0 # last 'A'
fB = 0 # first 'B'

for i in S:
  c = i.count('AB')
  # count 'B~*', 'B~A' '*~A'
  if i.find('B') == 0 and i.rfind('A') == len(i)-1:
    BA += 1
  elif i.find('B') == 0:
    fB += 1
  elif i.rfind('A') == len(i)-1:
    lA += 1
  cnt += c

# lA_fB = min(lA, fB)  
# r = min(abs(lA - fB), BA)
# n = max(0, (BA -r) // 2)

if BA > 0:
  cnt += BA -1
  if lA > 0:
    cnt += 1
    lA -= 1
  if fB > 0:
    cnt += 1
    fB -= 1

cnt += min(fB, lA)
print(cnt)

Submission status: Accepted

Solution code:
N = int(input())

count_ab = 0
count_fb = 0
count_ea = 0
count_fbea = 0
for i in range(N):
    s = input()
    for j in range(len(s)-1):
        if s[j:j+2] == "AB":
            count_ab += 1
    if s[0] == "B" and s[len(s)-1] == "A":
        count_fbea += 1
    elif s[0] == "B":
        count_fb += 1
    elif s[len(s)-1] == "A":
        count_ea += 1

ans = count_ab
if count_fbea > 0:
    ans += count_fbea - 1
    if count_fb > 0:
        count_fb -= 1
        ans += 1
    if count_ea > 0:
        count_ea -= 1
        ans += 1
ans += min(count_fb, count_ea)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
S = [input() for i in range(n)]
cnt = 0
a = 0
b = 0
ba = 0
for i in range(n):
    cnt += S[i].count("AB")
    if S[i].startswith("B") and S[i].endswith("A"):
        ba += 1
    elif S[i].startswith("B"):
        b += 1
    elif S[i].endswith("A"):
        a += 1
if ba >= 1:
    cnt += ba - 1
    if a >= 1:
        cnt += 1
        a -= 1
    if b >= 1:
        cnt += 1
        b -= 1
    cnt += min(a, b)
elif a >= 1 and b >= 1:
    cnt += min(a, b)
print(cnt)

Submission status: Accepted

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

ans = 0
firstB = 0
lastA = 0
cnt = 0
for s in S:
    if s[0] == 'B':
        firstB += 1
    if s[-1:] == 'A':
        lastA += 1

    if s[0] == 'B' and s[-1:] == 'A':
        cnt += 1

    ans += s.count('AB')
    
if cnt == max([firstB,lastA]) and cnt > 0:
    print(ans + cnt -1)
else:
    print(ans+ min([firstB,lastA]))

Submission status: Accepted

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

ans = 0
start_b = 0
end_a = 0
ab = 0

for i in range(n):
    for j in range(len(S[i]) - 1):
        if S[i][j:j+2] == 'AB':
            ans += 1

    if S[i][0] == 'B' and S[i][-1] == 'A':
        ab += 1
        continue 
    if S[i][0] == 'B':
        start_b += 1
    if S[i][-1] == 'A':
        end_a += 1
    

if ab > 0:
    ans += ab - 1
    if start_b > 0:
        ans += 1
        start_b -= 1
    if end_a > 0:
        ans += 1
        end_a -= 1
        
ans += min(start_b, end_a)

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = [input() for _ in range(n)]
 
counter = 0
begin_b = []
end_a = []
begin_b_and_end_a = []
for i in range(n):
    counter += s[i].count('AB')
    if s[i][0] == 'B':
        begin_b.append(i)
    if s[i][-1] == 'A':
        end_a.append(i)
    if s[i][0] == 'B' and s[i][-1] == 'A':
        begin_b_and_end_a.append(i)
 
if len(begin_b) == len(begin_b_and_end_a) and len(begin_b_and_end_a) == len(end_a) and len(end_a) > 0:
    print(counter + min(len(begin_b), len(end_a)) - 1)
else:
    print(counter + min(len(begin_b), len(end_a)))

Submission status: Accepted

Solution code:
n = int(input())
list = []
for i in range(n):
    keep = input()
    list.append(keep)
double = 0
b = 0
a = 0
include = 0
for j in range(n):
    if list[j][0] == "B" and list[j][-1:] == "A":
        double += 1
    elif list[j][0] == "B":
        b += 1
    elif list[j][-1:] == "A":
        a += 1

    keep_len = len(list[j])
    for k in range(keep_len-1):
        if list[j][k] == "A" and list[j][k+1] == "B":
            include += 1
if b == 0 and a == 0 and double == 0:
    print(include)
elif b == 0 and a == 0:
    print(double-1 + include)
elif b == 0 or a == 0:
    print(double-1 + include + 1)
else:
    print(double-1 + include + min(b, a) + 1)