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())
s = [input() for _ in range(N)]

k = sum(t.count('AB') for t in s)
ab = sum(t[-1] == 'A' and t[0] == 'B' for t in s)
a = sum(t[-1] == 'A' and t[0] != 'B' for t in s)
b = sum(t[-1] != 'A' and t[0] == 'B' for t in s)
ans = k
f = a > 0 or ab > 0
if a > 0 and ab > 0:
    ans += 1
    ab -= 1
    a -= 1
elif a == 0:
    ab -= 1
else:
    a -= 1
ans += ab
if f and b > 0:
    ans += 1
    b -= 1
ans += min(a, b)
print(ans)

Submission status: Wrong Answer

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

ABin=sum([checkAB(si) for si in s])
Aend=sum([si[len(si)-1]=='A' for si in s])
Bstart=sum([si[0]=='B' for si in s])
#print(ABin,Aend,Bstart)
print(ABin+min(N-1,Aend,Bstart))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
input = sys.stdin.readline
 
# bisect_left(lists, 3)
# bisect_right(lists, 3)
 
def main():
	#R, G, B, N = map(int, input().split(" "))
	N = int(input())

	S = []
	A = 0
	B = 0
	for _ in range(N):
		tmp = input()
		tmp = tmp[:-1]
		S.append(tmp)
		if tmp[0] == "B":
			B += 1
		if tmp[-1] == "A":
			A += 1

	ans = 0
	for i, val in enumerate(S):
		tmp = val.split("AB")
		ans = ans + len(tmp) -1
	
	print(ans + min(A, B))

	
	
if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
N = int(input())
ans,a,b = 0,0,0
for i in range(N):
  S = input()
  ans += S.count("AB")
  if S[0] == 'B':
    b += 1
  if S[-1] == 'A':
    a += 1
print(ans + (min(a,b) if N != a or N != b else a - 1))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
ca = 0
cb = 0
for i in range(n):
    tmp = input()
    s.append(tmp)
    if tmp[-1] == "A":
        ca += 1
    if tmp[0] == "B":
        cb += 1
cnt = 0
for i in range(n):
    cnt += s[i].count("AB")
if min(ca, cb) >= n - 2:
    cnt -= 1
print(cnt + min(ca, cb))

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [None] * N

count_AB = 0
right_A = 0
left_B = 0
right_A_left_B = 0

for i in range(N):
    s = input()
    count_AB += s.count('AB')
    if s[0] == "B" and s[-1] == "A":
        right_A_left_B += 1
    elif s[0] == "B":
        left_B += 1
    elif s[-1] == "A":
        right_A += 1

if right_A_left_B > 0:
    count_AB += (right_A_left_B - 1)
    right_A_left_B = 1
    # OK

min_AB = min(right_A, left_B)
count_AB += min_AB

# which one is 0
right_A = abs(right_A - min_AB)
left_B = abs(left_B - min_AB)

if right_A_left_B > 0 and (right_A + left_B) > 0:
    count_AB += 1
    right_A_left_B = 0
    if right_A > 0:
        right_A -= 1
        left_B += 1
    else:
        left_B -= 1
        right_A += 1
if left_B > 0 and right_A > 0:
    count_AB += 1

print(count_AB)

Submission status: Wrong Answer

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

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

if min(counta, countab) + min(countb, countab) < countab:
    res += countab
else:
    res += min(countab, counta)
    res += min(countab, countb)
counta, countb = max(0, counta - countab), max(0, countb - countab)
res += min(counta, countb)
print(res)

Submission status: Wrong Answer

Solution code:
n = int(input())
words = [str(input()) for i in range(n)]
counter = 0
beginb = 0
enda = 0
for word in words:
    for index, letter in enumerate(word):
        if index<len(word)-1:
            if word[index] == 'A' and word[index+1] == 'B':
                counter += 1
    if word[0] == "B":
        beginb += 1
    if word[-1] == "A":
        enda += 1
print(counter+min(beginb,enda))

Submission status: Wrong Answer

Solution code:
N = int(input())
inside_str = 0
tail_a = 0
head_b = 0

for i in range(N):
  str = input()
  ab_inside_str = str.count('AB')

  inside_str = inside_str + ab_inside_str
  if (str[-1] == "A"):
    tail_a = tail_a + 1
  if (str[0] == "B"):
    head_b = head_b + 1

total_cand = inside_str + min(tail_a, head_b)
print(total_cand)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = [input() for i in range(N)]
l1 = [s[i].count('AB') for i in range(N)]
l2 = [1 if s[i][0] == 'B' else 0 for i in range(N)]
l3 = [1 if s[i][-1] == 'A' else 0 for i in range(N)]
l4 = [l2[i]*l3[i] for i in range(N)]
if min(sum(l2),sum(l3)) == N:
    a = min(sum(l2),sum(l3))-1
else:
    a = min(sum(l2),sum(l3))
print(sum(l1) + a)

Submission status: Wrong Answer

Solution code:
N=input()

ans=0
r_a_cnt=0
l_b_cnt=0

for _ in range(N):
	s=raw_input()
	if s[0]=="B": l_b_cnt+=1
	if s[-1]=="A": r_a_cnt+=1

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

ans+=min(l_b_cnt, r_a_cnt)
print ans

Submission status: Wrong Answer

Solution code:
N = int(input())
A = 0
B = 0
AB = 0
ans = 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' and S[-1] == 'A':
        AB += 1
    elif S[0] == 'B':
        B += 1
    elif S[-1] == 'A':
        A += 1
    # print(S, A, B, AB, ans)
            
ans += min(A + AB, B + AB)
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())

count = 0
first_b = 0
last_a = 0
fl_ba = 0
for i in range(N):
    s = input()
    count += s.count('AB')
    b, a = s[0], s[-1]
    if b == 'B' and a == 'A':
        fl_ba += 1
    elif b =='B':
        first_b += 1
    elif a == 'A':
        last_a += 1

if fl_ba == 0:
    print(count + min(first_b, last_a))
elif first_b == last_a:
    print(count + min(first_b, last_a) + fl_ba-1)
else:
    print(count + min(first_b, last_a) + fl_ba)

Submission status: Wrong Answer

Solution code:
n = int(input())

g1 = []
g2 = []
g3 = []

cnt = 0

for i in range(n):
    s = input()
    cnt += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        g3.append(s)
    elif s[0] == "B":
        g1.append(s)
    elif s[-1] == "A":
        g2.append(s)
        
#print(cnt)

if len(g1) >= len(g2):
    cnt += len(g2)
    if len(g1) - len(g2) >= len(g3):
        cnt += len(g3)
    elif len(g3) > len(g1) - len(g2):
        cnt += len(g1) - len(g2)
elif len(g2) >= len(g1):
    cnt += len(g1)
    if len(g2) - len(g1) >= len(g3):
        cnt += len(g3)
    elif len(g3) > len(g2) - len(g1):
        cnt += len(g2) - len(g1)
        
if len(g3) - len(g2) - len(g1) > 0:
    cnt += len(g3) - len(g2) - len(g1)


print(cnt)

Submission status: Wrong Answer

Solution code:
N =int(input())
co = {0:0,1:0,2:0,3:0}
ans = 0
foo =0
for _ in range(N):
    i = input()
    foo = 0
    if i[0] =="B":
        foo += 1
    if i[-1] =="A":
        foo += 2
    co[foo] += 1
    ans += i.count("AB")
ans +=  min(co[1],co[2])
ans += co[3]
if co[1]==0 and co[2] == 0:
    ans -= 1
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=[input() for _ in range(n)]
isFinishA=[s[i][-1]=='A' for i in range(n)]
isStartB=[s[i][0]=='B' for i in range(n)]
ans=0
for si in s:
    isA=False
    for sij in si:
        if sij=='B':
            if isA:
                ans+=1
        isA=(sij=='A')

fromBtoA=0
for i in range(n):
    if isFinishA[i]:
        if isStartB[i]:
            fromBtoA+=1

cnt=[isFinishA.count(True),isStartB.count(True)]
ans+=min(cnt)
if cnt[0]==cnt[1]==fromBtoA:
    ans-=1
print(ans)

Submission status: Wrong Answer

Solution code:
#c
n = int(input())
stringsA = 0
stringsB = 0
both = 0
ans = 0
if n == 1:
    string = input()
    print(string.count("AB"))
else:
    for i in range(n):
        string = input()
        ans += string.count("AB")
        if string[-1] == 'A' and string[0] == 'B':
            both += 1
        elif string[-1] == 'A':
            stringsA += 1
        elif string[0] == 'B':
            stringsB += 1
    if both // 2 == 0:
        both = both //2
    else:
        both = both //2 + 1
    print(ans + min(stringsA,stringsB) + both)

Submission status: Wrong Answer

Solution code:
N=int(input())
s=[]
total=0
A=0
B=0
for i in range(N):
    tmp=input()
    while True:
        if len(tmp)>=2:
            if "AB" in tmp[:2]:
                total+=1
                tmp=tmp[2:]
            else:
                break
        else:
            break
    while True:
        
        if len(tmp)>=2:
            if "AB" in tmp[-2:]:
                total+=1
                tmp=tmp[-2:]
            else:
                break
        else:
            break
    total+=tmp.count("AB")
    if len(tmp)>0:
        if tmp[0]=="B":
            B+=1
        if tmp[-1]=="A":
            A+=1

print(total+min(A,B))

Submission status: Wrong Answer

Solution code:
import sys, os

f = lambda:list(map(int,input().split()))
if 'local' in os.environ :
    sys.stdin = open('./input.txt', 'r')

def solve():
    n = f()[0]
    ans = 0
    cnt_only_head_b = 0
    cnt_only_end_a = 0
    cnt_headb_enda = 0
    for i in range(n):
        s = input()
        slen = len(s)
        for j in range(slen-1):
            if s[j:j+2] == 'AB':
                ans += 1
            
        if s[0] == 'B' and s[-1]!='A':
            cnt_only_head_b += 1
        if s[-1] == 'A' and s[0]!='B':
            cnt_only_end_a += 1
        if s[0] == 'B' and s[-1] == 'A':
            cnt_headb_enda += 1

    

    minab = min(cnt_only_end_a, cnt_only_head_b)
    ans += minab
    cnt_only_end_a -= minab
    cnt_only_head_b -= minab


    if cnt_headb_enda:
        ans += cnt_headb_enda - 1

        if cnt_only_end_a or cnt_only_head_b:
            ans += 1

    print(ans)


    
    

solve()

Submission status: Wrong Answer

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

cnt_ab = 0
cnt_a = 0
cnt_b = 0

for i in range(N):
    cnt_ab += List[i].count("AB")
for j in range(N):
    if List[j][-1]=="A":
        cnt_a+=1
for k in range(N):
    if List[k][0]=="B":
        cnt_b +=1
        
cnt = cnt_ab+min(cnt_a, cnt_b)
print(cnt)

Submission status: Wrong Answer

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+min(cnt_a,cnt_b)
if cnt_bxa!=0:
  ans+=cnt_bxa-1
  if cnt_a>0:
    ans+=1
print(ans)

Submission status: Wrong Answer

Solution code:
n=0
tmp = ''
a=0
b=0
n = input()
l = 0
sum = 0
for i in n:
    tmp = input()
    l = len(tmp)
    if tmp[1] == 'B':
        b = b+1
    if tmp[l-1] == 'A':
        a = a+1
    
    tmpchar = ''
    for char in tmp:
        if char == 'B' and tmpchar == 'A':
            sum = sum +1
        tmpchar = char

if a==n and b ==n:
    a =a-1
if a>b:
    print(sum+b)
else: 
    print(sum + a)

Submission status: Wrong Answer

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:
  print(AB+B_A-1)
else:
  _AB_ = min(_A, B_)
  print(AB+_AB_)

Submission status: Wrong Answer

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

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

if ba >= 1:
    a += 1
    b += 1
    if ba >= 2:
        ab += ba - 1

ab += min([a, b])

print(ab)

Submission status: Wrong Answer

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):
    print(counter + min(len(begin_b), len(end_a)) - 1)
else:
    print(counter + min(len(begin_b), len(end_a)))

Submission status: Wrong Answer

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==B and B == 0:
    ans -= 1
print(ans)

Submission status: Wrong Answer

Solution code:
from sys import stdin
import numpy as np
 
N = int(input())
S = [input() for _ in range(N)]

cnt_innerAB = 0
cnt_endA = 0
cnt_firstB = 0

for i in range(N):
  cnt_innerAB += S[i].count('AB')
  if S[i][0] == 'B':
    cnt_firstB += 1
  if S[i][-1] == 'A':
    cnt_endA += 1

cnt_sideAB = min(cnt_endA, cnt_firstB, N-1)
ans = cnt_innerAB + cnt_sideAB

print(ans)

Submission status: Wrong Answer

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

answer=0
a=0
b=0
q=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
    if t[-1]=="A":
        a+=1
    if t[0]=="B" and t[-1]=="A":
        pass
    else:
        q=0

if a>b:
    print(answer+b-q)
else:
    print(answer+a-q)

Submission status: Wrong Answer

Solution code:
# from sys import exit
N = int(input())
S = [str(input()) for _ in range(N)]

Astart = set()
Bstart = set()
Aend = set()
Bend = set()
ABcon = set()
for s in S:
    if(s[0] == "B"):
        Bstart.add(s)
    if(s[-1] == "A"):
        Aend.add(s)
    if("AB" in s):
        ABcon.add(s)

canAB1 = min(len(Bstart), len(Aend))
print(canAB1 + len(ABcon))

Submission status: Wrong Answer

Solution code:
N=int(input())
S=[input() for _ in [0]*N]
AB=0
X_A=0
B_X=0
B_A=0
for s in S:
    AB+=s.count("AB")
    if s[0]!="B" and s[-1]=="A":X_A+=1
    if s[0]=="B" and s[-1]!="A":B_X+=1
    if s[0]=="B" and s[-1]=="A":B_A+=1
#print(AB,X_A,B_X,B_A)
print(AB + min(X_A,B_X) + (0 if B_A==0 else B_A-1+(1 if X_A-min(X_A,B_X)>0 else 0)+(1 if B_X-min(X_A,B_X)>0 else 0)))

Submission status: Wrong Answer

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

count = 0
aa = 0
bb = 0
for a in A:
    if a[0]=='B':
        aa+=1
    if a[-1]=='A':
        bb+=1
    count += a.count('AB')
if aa==bb and aa !=0 :
    aa -=1
count = count+min(aa,bb)
print(count)

Submission status: Wrong Answer

Solution code:
ans=0
a_end=0
b_start=0
flag_c=0

N=int(input())
for i in range(N):
    flag=0
    s=input()
    ans+=s.count("AB")
    if s[-1]=="A":
        a_end+=1
        flag+=1
    if s[0]=="B":
        b_start+=1
        flag+=1
        
    if flag==2:
        flag_c+=1
        
for i in range(flag_c):
    if a_end>=b_start:
        a_end+=1
    else:
        b_start+=1
        
print(ans+min(a_end,b_start))

Submission status: Wrong Answer

Solution code:
n = int(input())
cnt = 0
bx = 0
xa = 0
for i in range(n):
  si = input()
  flg = False
  for c in si:
    if c == 'A':
      flg = True
    elif c == 'B' and flg:
      cnt += 1
      flg = False
        
    else:
      flg = False
  
  if si[0] == 'B':
    bx += 1
  if si[-1] == 'A':
    xa += 1

print(cnt + min(bx, xa))

Submission status: Wrong Answer

Solution code:
from sys import stdin
    
def calc(s):
    lastA = 0
    firstB = 0
    both = 0
    interAB = 0
    for _s in s:
        if _s[0] == 'B' and _s[-1] == 'A':
            both += 1
        else:
            if _s[0] == 'B':
                firstB += 1
            if _s[-1] == 'A':
                lastA += 1
        
        if 'AB' in _s:
            interAB += 1

    if lastA == 0 and firstB == 0 and both == 1:
        return interAB
    
    return min(lastA + both, firstB + both) + interAB

def main():
    n = stdin.readline().rstrip()
    s = [x.rstrip() for x in stdin.readlines()]
    ans = calc(s)
    print(ans)
    
if __name__=='__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())
Ss=[input() for s in range(N)]
count = [s.count("AB") for s in Ss if "AB" in s]
headcount = len([s for s in Ss if s[0]=="B"])
outcount = len([s for s in Ss if s[-1]=="A"])
print(sum(count)+min(headcount,outcount))

Submission status: Wrong Answer

Solution code:
N = int(input())
Sa = 0
Sb = 0
Sab = 0
ans = 0
for i in range(N):
    t = input()
    if t[-1] == 'A':
        if t[0] == 'B': Sab += 1
        else: Sa += 1
    elif t[0] == 'B': Sb += 1
    ans += t.count('AB')
ans += Sab-1
if Sab > 0:
    if Sa < Sb: Sa += 1
    else: Sb += 1
ans += min(Sa,Sb)
print(ans)

Submission status: Wrong Answer

Solution code:

# coding: utf-8

# In[7]:

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


# In[10]:

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


# In[ ]:

Submission status: Wrong Answer

Solution code:
N = int(input())
ans = 0
ls = 0
rs = 0
lr = 0
for _ in range(N):
    s = str(input())
    if "AB" in s:
        ans += 1
    if s[-1] == "A" and s[0] == "B":
        lr += 1
    elif s[-1] == "A":
        rs += 1
    elif s[0] == "B":
        ls += 1
if ls == 0 and rs == 0:
    ans += lr - 1 
elif ls == 0 and rs != 0:
    ans += lr
elif ls != 0 and rs == 0:
    ans += lr
else:
    lr += 1
    rs -= 1
    ls -= 1
    ans += lr
    ans += (rs+ls)//2
#ans += lr
print(ans)

Submission status: Wrong Answer

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

print(ans+ab-1+min(min(a+1,b),min(a,b+1)))

Submission status: Wrong Answer

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

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 + x * 2 + both -x - 1 + int(y > 0))

Submission status: Wrong Answer

Solution code:
n = int(input())
a, b = 0, 0
ans = 0
for _ in range(n):
    s = str(input())
    if s[0] == 'B':
        b += 1
    if s[-1] == 'A':
        a += 1
    for i in range(len(s) - 1):
        if s[i: i + 2] == 'AB':
            ans += 1
ans += min(a, b)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

n = ni()
s = [ns() for _ in range(n)]

ans = 0

x = y = z = 0

for si in s:
    # 内部のABカウント
    ans += si.count('AB')

    # 右端A かつ 左端B ... Z
    if si[:1] == 'B' and si[-1:] == 'A':
        z += 1

    # 右端A ... X
    elif si[-1:] == 'A':
        x += 1

    # 左端B ... Y
    elif si[:1] == 'B':
        y += 1

if z < x and z < y:
    ans += 2*z
    ans += min(x,y) - z

else:
    ans += min(z, x)
    ans += min(z, y)

    if z > x and z > y:
        if z - max(x,y) <= max(x,y) - min(x,y):
            ans += z - max(x,y)
        else:
            ans += z - max(x,y)
            ans += 2 * ((z-max(x,y)) // 3)
            if (z-max(x,y)) % 3 == 2:
                ans += 1

print(ans)

Submission status: Wrong Answer

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

print(ans + min(a,b) if a!=ba else ans + min(a,b)-1)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

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

if bt > 0:
    ans += bt - 1
    ans += min(hd, tl)
    if hd != tl:
        ans += 1
    print(ans)
else:
    print(ans+min(hd, tl))

Submission status: Wrong Answer

Solution code:
# coding: utf-8
N = int(input())
s = []
for i in range(N):
    s.append(input().strip())


def n_ab(s):
    n = len(s)
    output = 0
    for i in range(n - 1):
        if s[i] + s[i+1] == "AB":
            output += 1

    return output


output = 0
for i in range(N):
    output += n_ab(s[i])

n_b = 0
n_a = 0
n_b_a = 0
for i in range(N):
    if s[i][0] == "B":
        if s[i][-1] == "A":
            n_b_a += 1
        else:
            n_b += 1
    elif s[i][-1] == "A":
        n_a += 1

output += n_b_a - 1

if n_a == 0:
    if n_b == 0:
        print(output)
    else:
        print(output+1)
else:
    if n_b == 0:
        print(output+1)
    else:
        print(output + 2 + min([n_b - 1, n_a - 1]))

Submission status: Wrong Answer

Solution code:
import sys

def inp():
  return sys.stdin.readline().strip()

N = int(inp())
inAB = 0
sB = 0
eA = 0
for _ in range(N):
  s = inp()
  inAB += s.count('AB')
  if s[0] == 'B':
    sB += 1
  if s[-1] == 'A':
    eA += 1

ans = inAB + min(sB, eA)
if N == sB == eA:
  ans -= 1
print(ans)

Submission status: Wrong Answer

Solution code:
N=int(input())
S=[]
count=0
for i in range(N):
    s=input()
    S.append(s)
    for k in range(len(s)-1):
        if s[k]=='A' and s[k+1]=='B':
            count+=1
a=0
for h in range(len(S)):
    if S[h][0]=='B':
        a+=1
b=0
for j in range(len(S)):
    if S[j][-1]=='A':
        b+=1
c=min(a,b)
print(count+c)

Submission status: Wrong Answer

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

A = 0
B = 0
BA = 0
ans = 0
for i in range(N):
    if S[i][0] == 'B' and S[i][-1] == 'A':
        BA += 1
    elif S[i][0] == 'B':
        B += 1
    elif S[i][-1] == 'A':
        A += 1
    for j in range(len(S[i])-1):
        if S[i][j] == 'A' and S[i][j+1] == 'B':
            ans += 1
if BA > 0:
    ans += BA - 1
    A += 1
    B += 1
ans += min(A, B)
print(ans)

Submission status: Wrong Answer

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

ct_a=0
ct_b=0
ct_ab=0
ct_ba=0

for i in range(N):
    if s[i][0]=='B' and s[i][1]=='A' and len(s[i])==2:
        ct_ba+=1
    elif s[i][0]=='B':
        ct_b+=1
    elif s[i][-1]=='A':
        ct_a+=1
    for j in range(len(s[i])-1):
        if s[i][j]=='A' and s[i][j+1]=='B':
            ct_ab+=1
    
print(ct_ab+min(ct_a,ct_b)+ct_ba-1)

Submission status: Wrong Answer

Solution code:
N=int(input())
s=[]
for i in range(N):
    s.append(input())
a=[0]*N
b=[0]*N
c=[0]*N
for i in range(N):
    a[i]=s[i].count('AB')
    if s[i][-1]=='A':
        b[i]=1
    else:
        pass
    if s[i][0]=='B':
        c[i]=1
B=sum(b)
C=sum(c)

print(sum(a)+ min(B,C))

Submission status: Wrong Answer

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

cnt1=0
B_Start=0
A_End=0
ALL=0

for i in range(N):
    cnt1 += S[i].count("AB")
    if S[i][0] == "B":
        B_Start += 1
    if S[i][-1] == "A":
        A_End += 1
    if S[i][0] == "B" or S[i][-1] == "A":
        ALL += 1

hosei=0
        
if B_Start == A_End == ALL:
  hosei=1
        
print(cnt1 + min(B_Start,A_End) - hosei)

Submission status: Wrong Answer

Solution code:
N = int(input())
counter = 0
end_a = 0
start_b = 0
start_b_end_a = 0
for n in range(N):
    s = input()
    for i in range(len(s) - 1):
        if s[i:i + 2] == 'AB':
            counter += 1
    if s[-1] == 'A':
        end_a += 1
    if s[0] == 'B':
        start_b += 1
    if s[-1] == 'A' and s[0] == 'B':
        start_b_end_a += 1
if N == start_b_end_a:
    print(counter + min([end_a, start_b]) - 1)
else:    
    print(counter + min([end_a, start_b]))

Submission status: Wrong Answer

Solution code:
import sys
# import bisect
# import math
# import itertools
# import numpy as np

# import collections

"""Template"""


class IP:
    """
    入力を取得するクラス
    """

    def __init__(self):
        self.input = sys.stdin.readline

    def I(self):
        """
        1文字の取得に使います
        :return: int
        """
        return int(self.input())

    def S(self):
        """
        1文字の取得(str
        :return: str
        """
        return self.input()

    def IL(self):
        """
        1行を空白で区切りリストにします(int
        :return: リスト
        """
        return list(map(int, self.input().split()))

    def SL(self):
        """
        1行の文字列を空白区切りでリストにします
        :return: リスト
        """
        return list(map(str, self.input().split()))

    def ILS(self, n):
        """
        1列丸々取得します(int
        :param n: 行数
        :return: リスト
        """
        return [int(self.input()) for _ in range(n)]

    def SLS(self, n):
        """
        1列丸々取得します（str
        :param n: 行数
        :return: リスト
        """
        return [self.input() for _ in range(n)]

    def SILS(self, n):
        """
        Some Int LineS
        横に複数、縦にも複数
        :param n: 行数
        :return: list
        """
        return [self.IL() for _ in range(n)]

    def SSLS(self, n):
        """
        Some String LineS
        :param n: 行数
        :return: list
        """
        return [self.SL() for _ in range(n)]


class Idea:
    def __init__(self):
        pass

    def HF(self, p):
        """
        Half enumeration
        半分全列挙です
        pの要素の和の組み合わせを作ります。
        ソート、重複削除行います
        :param p: list : 元となるリスト
        :return: list : 組み合わせられた和のリスト
        """
        return sorted(set(p[i] + p[j] for i in range(len(p)) for j in range(i, len(p))))

    def Bfs2(self, a):
        """
        bit_full_search2
        bit全探索の改良版
        全探索させたら2進数のリストと10進数のリストを返す
        :return: list２つ : １個目 2進数(16桁)  2個目 10進数
        """
        # 参考
        # https://blog.rossywhite.com/2018/08/06/bit-search/
        # https://atcoder.jp/contests/abc105/submissions/4088632
        value = []
        for i in range(1 << len(a)):
            output = []

            for j in range(len(a)):
                if self.bit_o(i, j):
                    """右からj+1番目のiが1かどうか判定"""
                    # output.append(a[j])
                    output.append(a[j])
            value.append([format(i, 'b').zfill(16), sum(output)])

        value.sort(key=lambda x: x[1])
        bin = [value[k][0] for k in range(len(value))]
        val = [value[k][1] for k in range(len(value))]
        return bin, val

    def S(self, s, r=0, m=-1):
        """
        ソート関係行います。色々な設定あります。
        :param s: 元となるリスト
        :param r: reversするかどうか 0=False 1=True
        :param m: （2次元配列）何番目のインデックスのソートなのか
        :return: None
        """
        r = bool(r)
        if m == -1:
            s.sort(reverse=r)
        else:
            s.sort(reverse=r, key=lambda x: x[m])

    def bit_n(self, a, b):
        """
        bit探索で使います。0以上のときにTrue出します
        自然数だからn
        :param a: int
        :param b: int
        :return: bool
        """
        return bool((a >> b & 1) > 0)

    def bit_o(self, a, b):
        """
        bit探索で使います。1のときにTrue出すよ
        oneで1
        :param a: int
        :param b: int
        :return: bool
        """
        return bool(((a >> b) & 1) == 1)

    def ceil(self, x, y):
        """
        Round up
        小数点切り上げ割り算
        :param x: int
        :param y: int
        :return: int
        """
        return -(-x // y)

    def ave(self, a):
        """
        平均を求めます
        :param a: list
        :return: int
        """
        return sum(a) / len(a)

    def gcd(self, x, y):
        if y == 0:
            return x
        else:
            return self.gcd(y, x % y)


"""ここからメインコード"""


def main():
    # 1文字に省略
    r, e, p = range, enumerate, print
    ip = IP()
    id = Idea()
    mod = 10 ** 9 + 7

    """この下から書いてね"""
    n = ip.I()
    ans = 0
    a = 0
    b = 0
    for i in range(n):
        o = input()
        res = o[:-1].count("AB")
        if res == -1:
            pass
        else:
            ans += res
        if o[-1] == 'A':
            a += 1
        if o[0] == 'B':
            b += 1
    try:
        ans += min(a, b)
    except ZeroDivisionError:
        pass
    p(ans)


main()

Submission status: Wrong Answer

Solution code:
N = int(input())
L = []
for n in range(N):
    L.append(input())
AB = 0
A = 0
B = 0
for n in range(N):
    if "AB" in L[n]:
        AB += 1
    if L[n][-1:] == "A":
        if L[n][0] == "B":
            A += 1
            B += 1
        else:
            A += 1
    elif L[n][0] == "B":
        B += 1

print(min(A,B) + AB)