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: Wrong Answer

Solution code:
N = int(input())

cnt = 0
l = 0
r = 0
b = 0
for i in range(N):
    s_i = input()
    cnt += s_i.count("AB")

    if s_i[0] == "B" and s_i[len(s_i) - 1] == "A":
        b += 1
    elif s_i[0] == "B":
        l += 1
    elif s_i[len(s_i) - 1] == "A":
        r += 1
    else:
        continue

p = min(l, r)
m = max(l, r)
rest = m - p

if b > 0:
    cnt += b - 1
if rest > 0:
    cnt += 1
cnt += p

print(cnt)

Submission status: Wrong Answer

Solution code:
import re
N = int(input())
s=[input() for _ in range(N)]

counter = 0
for n in range(N):
    counter += len(re.findall('AB', s[n]))
lb_ra = 0
lb = 0
ra = 0
if N>1:

    for n in range(N):
        l, r = s[n][0]=='B', s[n][-1]=='A'
        if l and r:
            lb_ra += 1
        elif l:
            lb += 1
        elif r:
            ra +=1

    lb+=lb_ra
    ra+=lb_ra

print(counter+min(lb,ra))

Submission status: Wrong Answer

Solution code:
n=int(input())

#normal, start_b, end_a, both

kosu=0
tokushu=[0,0,0,0]

for i in range(n):
    line=input()
    switch=0
    for l in range(len(line)):
        if switch==1:
            if line[l]=='B':
                kosu+=1
            else:
                switch=0
        if line[l]=='A':
            switch=1
    
    if line[0]=='B':
        if line[-1]=='A':
            tokushu[3]+=1
        else:
            tokushu[1]+=1
    else:
        if line[-1]=='A':
            tokushu[2]+=1
        else:
            tokushu[0]+=1

#print(kosu)
#print(tokushu)
"""
if tokushu[3]>=1:
    mazu=tokushu[3]-1
    
else:
    mazu=0
"""
if tokushu[1]>tokushu[2]:
    gacchi=tokushu[2]
    nokori=tokushu[1]-gacchi
    if nokori==0 and tokushu[3]>0:
        gacchi2=tokushu[3]-1
    elif nokori>=tokushu[3]:
        gacchi2=tokushu[3]
    else:
        gacchi2=tokushu[3]
elif tokushu[1]==tokushu[2]:
    if tokushu[1]==0:
        gacchi=0
        gacchi2=tokushu[3]-1
    else:
        gacchi=tokushu[1]
        gacchi2=tokushu[3]
else:
    gacchi=tokushu[1]
    nokori=tokushu[2]-gacchi
    if nokori==0 and tokushu[3]>0:
        gacchi2=tokushu[3]-1
    elif nokori>=tokushu[3]:
        gacchi2=tokushu[3]
    else:
        gacchi2=tokushu[3]

#print(kosu,gacchi,gacchi2)
print(kosu+gacchi+gacchi2)

Submission status: Wrong Answer

Solution code:
n = int(input())
c = 0
st = 0
en = 0
for x in range(n):
	s = input()
	c += s.count("AB")
	if s[0] == "B": st += 1
	if s[-1] == "A": en += 1
print(c + min(st,en,n-(n%2)))

Submission status: Wrong Answer

Solution code:
def check(S):
    ans = 0
    for i in range(1,len(S)):
        if S[i-1] == 'A' and S[i] == 'B':
            ans += 1
    return ans

N = int(input())
s = []
a = 0
b = 0
ab = 0

ans = 0

for i in range(N):
    S = input()
    ans += check(S)
    if S[0] == 'B' or S[-1] == 'A':
        s.append(S)
        if S[0] == 'B' and S[-1] != 'A':
            b += 1
        elif S[0] != 'B' and S[-1] == 'A':
            a += 1
        else:
            ab += 1

if ab >= 2:
    ans += ab - 1
    ab = 1

ans += min(a,b)
abc = abs(a-b)
if abc >= 1:
    ans += 1

print(ans)

Submission status: Wrong Answer

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


N = int(input())

head_b_count = 0
tail_a_count = 0

head_b_tail_a_count = 0

total = 0

for _ in range(N):

    s = input()

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

    total += s.count('AB')

additional = min(head_b_count, tail_a_count)

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

total += additional

print(total)

Submission status: Wrong Answer

Solution code:
n=int(input())  #数値入力
listA=[] #appendのために宣言が必要
for i in range(n):
    listA.append(input())
# print(listA)

ABin = 0
__A = 0
B__ = 0
A_B = 0
for string in listA:
    if 'AB' in string:
        ABin += 1
    if string[-1] == 'A' and string[0] == 'B':
        A_B += 1
    if string[-1] == 'A' and string[0] != 'B':
        __A += 1
    if string[0] == 'B' and string[-1] != 'A':
        B__ += 1
    
# print(ABin,A_B,__A,B__)
if A_B == n:
    print(n-1)
else:
    print(ABin + min(__A,B__)+A_B)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [input() for _ in range(N)]
ab = 'AB'
A = []
ans = 0
for s in S:
  start = 0
  last = 0
  if('B' == s[0]):
    start = 1
  if('A' == s[-1]):
    last = 1
  if(start == 1 or last == 1):
    A.append(str(start + last * 2))
  a = len(s.split(ab))
  ans += (a-1)
f = False
if '2' in A:
  f = True
for s in A:
  if(s == '3' and f):
    ans += 1
  else:
    f = True
if '1' in A:
  ans += 1

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [str(input()) for i in range(n)]
p = 0
q = 0
k = 0
l = 0

for i in range(n):
    if s[i][0] == 'B':
        if s[i][len(s[i]) - 1] == 'A':
            l = l + 1
        else:
            p = p + 1
    elif s[i][len(s[i]) - 1] == 'A':
        q = q + 1
    
    for r in range(len(s[i]) - 2):
        if s[i][r] =='A' and s[i][r + 1] == 'B':
            k = k + 1

print(min(p, q) + max(l - 1, 0) + abs(p - q) + k)

Submission status: Wrong Answer

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

a = 0
b = 0
ba = 0
n = 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
    n += s.count("AB")

if a == 0:
    ba -= 1
    a += 1
if b == 0:
    ba -= 1
    b += 1
print(n + min(ba+a,ba+b))

Submission status: Wrong Answer

Solution code:
#python 3.5.2

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

Submission status: Wrong Answer

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]==c[1] and c[1]==c[2]:
  plus=c[2]-1
else:
  plus=min(c[0],c[1])
print(cnt+plus)

Submission status: Wrong Answer

Solution code:
import collections

N = int(input())

count = 0
count_first = 0
count_last = 0
for i in range(N):
    str = input()
    count += str.count("AB")
    if "B" == str[0]:
        count_last += 1
    if "A" == str[-1]:
        count_first +=1

print(count+min(count_first, count_last))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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
print(sum + max(sum_a, sum_b) + sum_ab - 1)

Submission status: Wrong Answer

Solution code:
def solve():
    N = int(input())
    S = [input() for _ in range(N)]
    AB_count = 0
    # 元から含まれているABの計算
    head_B = 0
    tail_A = 0
    head_B_count = 0
    tail_A_count = 0
    B_and_A_count = 0
    for si in S:
        head_B_flg = False
        tail_A_flg = False
        # print(si.count('AB'))
        AB_count += si.count('AB')
        # print(list(si)[0], list(si)[-1])
        list_si = list(si)
        if list_si[0] == 'B' and list_si[-1] == 'A':
            B_and_A_count += 1
            pass
        elif list(si)[0] == 'B':
            head_B_count += 1
        elif list(si)[-1] == 'A':
            tail_A_count += 1
    if B_and_A_count > 0:
        AB_count += B_and_A_count - 1
        if head_B_count > 0:
            AB_count += 1
            head_B_count -= 1
        if tail_A_count > 0:
            AB_count += 1
            tail_A_count -= 1
        AB_count += min(head_B_count, tail_A_count)
    print(AB_count)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:

# coding: utf-8

# In[17]:

import sys
#input = sys.stdin.readline
N = int(input())
S = [input() for i in range(N)]


# In[18]:

b_cnt = 0
a_cnt = 0
ab_cnt = 0
for i in range(N):
    if S[i][0]=='B'and S[i][-1]=='A':
        ab_cnt += 1
    elif S[i][0]=='B':
        b_cnt += 1
    elif S[i][-1]=='A':
        a_cnt += 1
#print(b_cnt, a_cnt)
#print(ab_cnt, a_cnt, b_cnt, '/'.join(S).count('AB') )

#if abs(a_cnt-b_cnt) >= 1 and ab_cnt > 0:

if max(a_cnt, b_cnt) == 0 and ab_cnt > 0:
    ab_cnt -= 1
elif min(a_cnt, b_cnt) > 0 and ab_cnt > 0:
    ab_cnt += 1
elif abs(a_cnt-b_cnt) == 0 and ab_cnt > 0:
    ab_cnt += 1
elif abs(a_cnt-b_cnt) > 0 and ab_cnt > 0:
    ab_cnt += 0
    
#if ab_cnt < 0:
#    ab_cnt = 0
#ab_cnt = ab_cnt-1 if ab_cnt!=0 else ab_cnt
print('/'.join(S).count('AB') + min(a_cnt, b_cnt, N-1) + ab_cnt)


# In[ ]:

Submission status: Wrong Answer

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 max(firstB,lastA)!=0:
    if firstB==lastA:
        ans+=(bothAB+firstB)
    else:
        ans+=min(firstB,lastA)+bothAB
else:
    ans+=(bothAB-1)

print(ans)

Submission status: Wrong Answer

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

for s in S:
  if "AB" in s:
    cnt1 += s.count("AB")
  if s[0] == "B":
    cnt2 += 1
  if s[-1] == "A":
    cnt3 += 1

print(cnt1 + min(cnt2, cnt3) if not (cnt2 == cnt3 == N) else cnt1 + min(cnt2, cnt3) - 1)

Submission status: Wrong Answer

Solution code:
n=int(input())
ans=0
fla=0
flb=0
for x in range(n):
    s = input()
    if 'AB' in s:
        ans += s.count('AB')
    if s[-1]=='A':
        fla+=1
    if s[0]=='B':
        flb+=1
ans+=min(fla,flb)
print(ans)

Submission status: Wrong Answer

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

count = 0
a_count = 0
b_count = 0
for i in range(len(s_list)):
    count += s_list[i].count("AB")
    if s_list[i][-1] == "A":
        a_count += 1
    if s_list[i][0] == "B":
        b_count += 1

if a_count > b_count :
    print(count + b_count)
else :
    print(count + a_count)

Submission status: Wrong Answer

Solution code:
N = int(input())
AB_number = 0
ab_cnt =0
a_cnt = 0
b_cnt = 0
for _ in range(N):
    s_i = input()
    AB_number += s_i.count("AB")
    if s_i[0] == "B" and s_i[-1] == "A":
        ab_cnt += 1
    elif s_i[-1] == "A":
        a_cnt += 1
    elif s_i[0] == "B":
        b_cnt += 1

if ab_cnt== 0:
    print(AB_number+min(a_cnt,b_cnt))
    print(AB_number+min(a_cnt,b_cnt)-1)
elif a_cnt != b_cnt:
    print(AB_number+(ab_cnt-1)+1+min(a_cnt,b_cnt))
else:
    print(AB_number+(ab_cnt-1)+min(a_cnt,b_cnt))

Submission status: Wrong Answer

Solution code:
n = int(input())
cnt = 0
acnt = 0
bcnt = 0
for i in range(n):
  a = input()
  b = len(a)
  if a[0] == "B":
    bcnt+=1
  if a[b-1] == "A":
    acnt+=1
  for j in range(b-1):
    if a[j] == "A" and a[j+1] == "B":
      cnt+=1
print(min(acnt,bcnt)+cnt)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = [input() for i in range(N)]
count = 0
l = []
a = 0
b = 0
ab = 0
for i in s:
  count+=i.count("AB")
for i in s:
  if list(i)[0] == "B" and list(i)[-1] != "A":
    l.append(i)
    b += 1
  elif list(i)[-1] == "A" and list(i)[0] != "B":
    l.append(i)
    a += 1
  elif list(i)[-1] == "A" and list(i)[0] == "B":
    l.append(i)
    ab += 1
if a > b + ab:
  count += b + ab
elif b > a + ab:
  count += a + ab
else:
  count += max(a, b, ab)
print(count)

Submission status: Wrong Answer

Solution code:
n = int(input())
ans = 0
ast = 0
bst = 0
for i in range (n) :
  s = input()
  a = s.count("A")
  b = s.count("B")
  plus = abs(a-b)
  ast += min ( a - plus , 2 )
  bst += min ( b - plus , 2 )
  ans += plus
tas = min(abs(ast-bst) , n-1 )
ans += tas
print(ans)

Submission status: Wrong Answer

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

check = [0] * N 
candidate = 0
special = 0

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


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




if special > 0:
    ans += special - 1
    if counta > countb:
        countb += 1
    elif countb > counta:
        counta += 1

if counta > countb:
    ans += countb
elif countb > counta:
    ans += counta
else:
    ans += counta


print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())

ans=0
ba=0
bstart=0
aend=0
for i in range(n):
  s=input()
  for j in range(len(s)):
    if s[j]=="A":
      if not j+1==len(s):
        if s[j+1]=="B":
          ans+=1
  
  if s[0]=="B" and s[-1]=="A":
    ba+=1
  else:
    if s[0]=="B":
      bstart+=1
    if s[-1]=="A":
      aend+=1
if ba==0:
  print(ans+min(bstart,aend))
else:
  if bstart>=1 and aend>=1:
    print(ans+ba-1+2+min(bstart-1,aend-1))
  else:
    print(ans+ba-1+max(bstart,aend))

Submission status: Wrong Answer

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

count += countBA-1 + min(countA,countB)+1  
print(count)

Submission status: Wrong Answer

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_ > 0 and _A > 0 and B_A > 0:
        print(AB + max((B_A - 1), 0) + max(min(B_ + int(B_A > 0), _A), min(B_, _A + int(B_A > 0))) + 1)
    else:
        print(AB + max((B_A - 1), 0) + max(min(B_ + int(B_A > 0), _A), min(B_, _A + int(B_A > 0))))
    # print(AB, B_, _A, B_A)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from io import StringIO
from collections import *
from functools import *
import sys


def main(inputs):
    n = int(next(inputs))
    ss = ( next(inputs) for _ in range(n) )
    ans = 0
    B__ = 0
    __A = 0
    B_A = 0
    for s in ss:
        ans += s.count("AB")
        b__ = (s[0] == "B")
        __a = (s[-1] == "A")
        if b__ and __a:
            B_A += 1
        else:
            B__ += b__
            __A += __a
            pass
        pass
    x = min(B__, __A)
    ans += x
    y = max(B__, __A) - x
    if y > 0 and B_A > 0:
        ans += B_A
    elif B_A >= 2:
        ans += B_A - 1
        pass
    #print("{}".format((ans, B__, __A, B_A)))
    return ans


def gen_inputs(str_=None):
    inputs = StringIO(str_) if str_ else sys.stdin
    while True:
        a = inputs.readline().rstrip()
        yield a
        pass
    pass


if __name__ == "__main__":
    print(main(gen_inputs()))
    pass

Submission status: Wrong Answer

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

abf = 0
af = 0
bf = 0
ans = 0
for i in range(N):
  s_i = slist[i]
  ans += s_i.count("AB")
  if (s_i[0] == "B") and (s_i[-1] == "A"):
    abf+=1
  elif s_i[0] == "B":
    bf+=1
  elif s_i[-1] == "A":
    af+=1

if (abf > af):
  ans += af
if (abf > bf):
  ans += bf

print(ans)

Submission status: Wrong Answer

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 != numB and numAB > 0:
    count += 1
print(count)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
import re

N = int(input())
string_list = [input() for i in range(N)]
count = 0
A_count = 0
B_count = 0
for i in string_list:
    count += len(re.findall('AB', i))
    if i[-1] == 'A':
        A_count += 1
    if i[0] == 'B':
        B_count += 1
if A_count < B_count:
    count += A_count
elif A_count > B_count:
    count += B_count
print(count)

Submission status: Wrong Answer

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

S.sort(key=lambda s: not s.endswith('A'))

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:
        ans += both_ab - 1
    else:
        ans += both_ab
else:
    ans += min(endswith_a, startswith_b)

print(ans)

Submission status: Wrong Answer

Solution code:
# coding: utf-8

import sys
input = sys.stdin.readline

N = int(input())
# L = [int(x) for x in input().split()]
# N, K = map(int, input().split())

AB  = 0
xA = 0
BxA = 0
Bx = 0

for _ in range(N) :
    S = input()

    AB += S.count("AB")

    if S[0] + S[-2] == "BA" :
        BxA += 1
    elif S[-2] == 'A' :
        xA += 1
    elif S[0] == 'B' :
        Bx += 1

if BxA < 1 :
    print(AB + min(xA, Bx))
elif xA > 0 and Bx > 0 :
    print(AB + (BxA - 1) + 2 + min(xA - 1, Bx - 1))
else :
    print(AB + (BxA - 1) + 1)

Submission status: Wrong Answer

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:
    if 'AB' in s:
        counter += 1
    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:
    counter += ab - 1
else:
    counter += c + ab

print(counter)

Submission status: Wrong Answer

Solution code:
N = int(input())
count = 0
topB = 0
bottomA = 0
for i in range(N):
    s = str(input())
    count += s.count("AB")
    if s[0] == "B":
        topB += 1
    if s[-1] == "A":
        bottomA += 1
if min(topB,bottomA) != N:
    print(count + min(topB,bottomA))
else:
    print(count + min(topB,bottomA)-1)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
"""<https://github.com/cheran-senthil/PyRival>"""
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    _str = str
    str = lambda x=b"": x if type(x) is bytes else _str(x).encode()


def main():
    n = int(input())

    a = b = c = m = 0

    for i in range(n):
        s = input()
        m += s.count('AB')
        if s[-1] == 'A' and s[0] == 'B':
            c += 1
        else:
            a += s[-1] == 'A'
            b += s[0] == 'B'

    t = min(a, b)

    m += t

    a -= t
    b -= t

    m += bool(c and (a or b)) + max(0, c - 1)

    print(m)


# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._buffer = BytesIO()
        self._fd = file.fileno()
        self._writable = "x" in file.mode or "r" not in file.mode
        self.write = self._buffer.write if self._writable else None

    def read(self):
        if self._buffer.tell():
            return self._buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self._buffer.tell()
            self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
        self.newlines -= 1
        return self._buffer.readline()

    def flush(self):
        if self._writable:
            os.write(self._fd, self._buffer.getvalue())
            self._buffer.truncate(0), self._buffer.seek(0)


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()


sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")

# endregion

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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_ == len(s) and a == len(s) and b == len(s):
  print(ab+a-1)
else:
  print(ab+min([a,b]))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/python3

n = int(input())

cnt=0
cnt_a=0
cnt_b=0

for i in range(n):
    s=input()
    cnt += s.count("AB")
    if s[-1]=='A':
        cnt_a+=1;
    if s[0]=='B':
        cnt_b+=1;

cnt += min(cnt_a,cnt_b)

print(cnt)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
AtCoder C
"""

# N = int(input())
# A = list(map(int,input().split())) # N row 1 column
# A = int(input()) for _ in range(N) # 1 row N column

# S = str(input()) # str(input()) == input() -> 'abc'
# S = list(input()) # abc -> ['a','b','c']

def main():
    # A, B = list(map(int,input().split()))
    N = int(input())
    S = [input() for _ in range(N)]# 1 row N column
    tmp=0
    a=0
    b=0
    for s in S:
        tmp+=s.count('AB')
        if s[0]=="B":
            a+=1
        if s[-1]=="A":
            b+=1
    print(tmp+min(a,b,N-1))
    
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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
else:
    answer=org_num+BA_num+BX_num_addition-1

XA_num-=1
BX_num-=1

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

answer+=shiage
print(answer)

Submission status: Wrong Answer

Solution code:
n=int(input())
numA=0
numB=0

def check(s):
    if not "AB" in s:
        return 0
    cnt=0
    for a,b in zip(s[:-1],s[1:]):
        if a=="A" and b=="B":
            cnt+=1
    return cnt

ans=0
for i in range(n):
    s=input()
    ans+=check(s)
    if s[0]=="B":
        numB+=1
    if s[-1]=="A":
        numA+=1
    
print(ans+min(numA,numB))

Submission status: Wrong Answer

Solution code:
n=int(input())
li=[]
t=0
for i in range (0,n):
  m=input()
  t=t+m.count("AB")
  li.append(list(m))
las=0
sta=0
q=0
for i in range (0,n):
  p=0
  le=len(li[i])-1
  if li[i][0]=="B":
    sta=sta+1
    p=p+1
  if li[i][le]=="A":
    las=las+1
    p=p+1
  if p==2:
    q=q+1
if sta==las==q:
  print(t+q-1)
elif sta==q:
  print(t+las)
elif las==q:
  print(t+sta)
elif sta<las:
  print(t+sta)
elif sta>las:
  print(t+las)
else:
  print(t+sta)

Submission status: Wrong Answer

Solution code:
n=int(input())
b_start=0
a_last=0
both=0
ans=0
for i in range(n):
    s=input()
    ans+=s.count("AB")
    if s[0]=="B":
        if s[len(s)-1]=="A":
            both+=1
        else:
            b_start+=1
    elif s[len(s)-1]=="A":
        a_last+=1
diff=abs(b_start-a_last)
# print(a_last, b_start, both, ans, diff)
ans+=both-1
if a_last>=1:
    ans+=1
    a_last-=1
if b_start>=1:
    ans+=1
    b_start-=1
ans+=min(a_last,b_start)
print(ans)
# if diff==0:
#     print(1)
#     print(max(b_start,a_last)+max(0,(both-1))+ans)
# elif diff >= both:
#     print(2)
#     print(min(b_start,a_last)+both+ans)
# else:
#     print(3)
#     print(max(b_start,a_last)+(both-diff)+ans)

Submission status: Wrong Answer

Solution code:
import math
N = int(input())
counter = 0
master_parts = 0
a_parts = 0
b_parts = 0
for i in range(N):
    temp = input()
    counter += temp.count('AB')
    if temp[-1] == 'A' and temp[0] == 'B':
        master_parts += 1
    elif temp[-1] == 'A':
        a_parts += 1
    elif temp[0] == 'B':
        b_parts += 1
if a_parts <= b_parts:
    if master_parts <= a_parts:
        a_parts -= master_parts
        counter += a_parts + master_parts * 2
    else:
        counter += a_parts + (master_parts - a_parts) / 2
        if b_parts-a_parts:
            counter += 1
if b_parts < a_parts:
    if master_parts <= b_parts:
        b_parts -= master_parts
        counter += b_parts + master_parts * 2
    else:
        counter += b_parts + (master_parts-b_parts)/2
        if a_parts-b_parts:
            counter += 1

print(math.ceil(counter))

Submission status: Wrong Answer

Solution code:
from sys import stdin

def main():
    N = int(input())
    S = stdin.read().splitlines()

    s1 = {'la':0, 'lb':0, 'ba':0}
    ans = 0
    for s in S:
        ans += s.count('AB')
        if s[0] == 'B' and s[-1] == 'A':
            s1['ba'] += 1
        elif s[0] == 'B':
            s1['lb'] += 1
        elif s[-1] == 'A':
            s1['la'] += 1
    min_, max_ = min(s1['la'], s1['lb']), max(s1['la'], s1['lb'])
    s1['ba'] -= max_ - min_
    ans += max_ + s1['ba']
    print(ans)

input = lambda: stdin.readline().rstrip()
main()

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

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

x = ','.join(S).count('AB')

A = [ s[-1] == "A" for s in S ].count(True)
B = [ s[0] == "B" for s in S ].count(True)
AandB = [ s[-1] == "A" and s[0] == "B" for s in S ].count(True)
for i in range(AandB):
  if A < B:
    A+=1
  else:
    B+=1
y = min( A, B ) - AandB

print(x + y)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
s = []
counter = 0
counter_AB = 0
counter_A = 0
counter_B = 0

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

for n in range(N):
    tmp = s[n]
    counter += tmp.count("AB")

    if tmp[0] == "B":
        counter_B += 1
    
    if tmp[len(tmp)-1] == "A":
        counter_A += 1

counter_min = min(counter_A, counter_B)

print(counter + counter_min)

Submission status: Wrong Answer

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

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

    ans += s.count('AB')

print(ans+ min([firstB,lastA]))

Submission status: Wrong Answer

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

print(count+xx)

Submission status: Wrong Answer

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

for i in range(N):
    L.append(input())
    

a = 0
b = 0
ab = 0
ans = 0
all_tail_b_a = True
for i in range(N):
    s = L[i]
    ab = s.count("AB")
    ans += ab

    if s[0] is "B":
        b += 1
    if s[-1] is "A":
        a += 1
        
    if s[0] is not "B" or s[-1] is not "A":
        all_tail_b_a = False

ans += min(a, b)
if all_tail_b_a is True:
    ans -= 1

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
c = 0
st = 0
en = 0
for x in range(n):
	s = input()
	c += s.count("AB")
	if s[0] == "B": st += 1
	if s[-1] == "A": en += 1
print(c + min(st,en,n))