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:
import re
N = int(input())
S = [input() for i in range(N)]
nAB = sum(map(lambda x: x.count('AB'), S))
lastB = sum(map(lambda x: x[0] == 'B', S))
firstA = sum(map(lambda x: x[-1] == 'A', S))
matchAB = sum(map(lambda x: x[0] == 'B' and x[-1] == 'A', S))
if min(lastB, firstA) == 0:
    print(nAB)
elif matchAB - min(lastB, firstA) == 0:
    print(nAB+min(lastB, firstA)-1)
else:
    print()
    print(nAB+min(lastB, firstA))

Submission status: Wrong Answer

Solution code:
n=int(input())
c1=c2=c3=0
c=0
for i in range(n):
  s=input()
  c+=s.count('AB')

  if s[0]=='B' and s[-1]=='A':
    c3+=1
  elif s[0]=='B':
    c1+=1
  elif s[-1]=='A':
    c2+=1

c+=max(0,c3-1)
if c1<c2:
  c+=c1
  if c2>0 and c3>0:
    c+=1
elif c1==c2:
  c+=c1
else:
  c+=c2
  if c1>0 and c3>0:
    c+=1

print(c)

Submission status: Wrong Answer

Solution code:
i = 1
n = input("")
num = int(n)
string = input("")
array = [string]
while i < num :
  strtemp = input("")
  array.append(strtemp)
  i+=1
front = 0
back = 0
is_a = 0
is_b = 0
is_ab = 0
for tmp in array :
  char = list(tmp)
  for tmp2 in char :
    if tmp2 == "A" :
      is_a = 1
      is_b = 0
    if is_a == 1 and tmp2 == "B" :
      is_ab += 1
      is_a = 0
    else :
      is_a = 0
      is_b = 1
      if char[0] == tmp2 :
        front += 1
  if is_a == 1 :
    back += 1
  is_a = 0
  is_b = 0
if front >= back :
  is_ab += back
elif back > front :
  is_ab += front
print(is_ab)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

contained = sum([s.count('AB') for s in ss])
B_hoge = sum([1 for s in ss if s[0]=='B'])
hoge_A = sum([1 for s in ss if s[-1]=='A'])
B_hoge_A = sum([1 for s in ss if s[0]=='B' and s[-1]=='A'])

B_hoge -= B_hoge_A
hoge_A -= B_hoge_A
gap = abs(B_hoge - hoge_A)
# 差がB_hoge_Aより大きい場合、可能な限り差を埋める
if gap >= B_hoge_A:
    print(contained + min(B_hoge,hoge_A) + B_hoge_A)
#　差がB_hoge_Aより小さい場合、差を埋めた残りでペアを作る
else:
    print(contained + max(B_hoge,hoge_A) + (B_hoge_A+1 - gap)//2)

# print('contained:',contained)
# print(B_hoge, hoge_A, B_hoge_A)

Submission status: Wrong Answer

Solution code:
N = int(input())
ans = 0
numb = 0
numa = 0
numba = 0
for _ in range(N):
    s = input()
    ans += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        numba += 1
    elif s[0] == "B":
        numb += 1
    elif s[-1] == "A":
        numa += 1
ans += min(numb, numa)
if abs(numb - numa) > 0:
    ans += numba
else:
    ans += max(0, numba - 1)
print(ans)

Submission status: Wrong Answer

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

cnt = 0
cntA = 0
cntB = 0
cntAB = 0

for s in S :
    for i in range(1, len(s)) :
        if s[i - 1] =='A' and s[i] == 'B':
            cnt += 1
    if s[0] == 'B' and s[len(s) - 1] == 'A':
        cntAB += 1
    elif s[0] == 'B' :
        cntA += 1
    elif s[len(s) - 1] == 'A' :
        cntB += 1

ans = min(cntA + cntAB, cntB + cntAB)
if ans == len(S) :
    ans -= 1
print(cnt + ans)

Submission status: Wrong Answer

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":
        p += 1
    if s[i][-1]=="A":
        q += 1
    if s[i][0]== "B" and s[i][-1]=="A":
        r +=1

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
a = 0  # Aで終了
b = 0  # Bで開始
ans = 0
for _ 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))

Submission status: Wrong Answer

Solution code:
N = int(input())
a, b, ab = 0, 0, 0

for i in range(N):
    s = input()
    if s[-1] == 'A':
        a += 1
    if s[0] == 'B':
        b +=1
    ab += s.count('AB')

if a>b :
    print(ab+b)
elif a==b:
    print(ab+a-1)
else: 
    print(ab+a)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
# f1: B....X
# f2: X....A
# f3: B....A
f1, f2, f3 = 0, 0, 0
ans = 0
for i in range(n):
    t = input(); s.append(t)
    ans += t.count("AB")
    if t[0] == "B" and t[-1] != "A":
        f1 += 1
    if t[0] != "B" and t[-1] == "A":
        f2 += 1
    if t[0] == "B" and t[-1] == "A":
        f3 += 1
if f1 == 0:
    ans += min(f2, f3)
    t = min(f2, f3)
    f2 -= t
    f3 -= t
    ans += f3
elif f2 == 0:
    ans += min(f1, f3)
elif f3 == 0:
    ans += min(f1, f2)
else:
    ans += min(f2, f3)
    t = min(f2, f3)
    f2 -= t
    f3 -= t

    if f3 == 0:
        f2 += 1
        ans += min(f1, f2)
    elif f2 == 0:
        ans += f3
        ans += 1

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())

S = list()
count = 0
acount = 0
bcount = 0
for _ in range(N):
    st = input()
    count += st.count('AB')
    S.append(st)
    if st.startswith('B'):
        bcount += 1
    if st.endswith('A'):
        acount += 1

if acount == N:
    c = acount - 1
elif bcount == N:
    c = bcount - 1
else:
    c = min(acount, bcount)
print(count + c)

Submission status: Wrong Answer

Solution code:
N = int(input())
count = 0
tail_A = 0
head_B = 0
B_A = 0
for _ in range(N):
    s = input()
    if s.find('AB') >= 0:
        count += 1
    if s[-1] == 'A':
        if s[0] == 'B':
            B_A += 1
        else:
            tail_A += 1
    else:
        if s[0] == 'B':
            head_B += 1

if tail_A > 0 and head_B > 0:
    count = count + B_A + 1
    tail_A -= 1
    head_B -= 1
elif tail_A == 0 and head_B > 0:
    count = count + B_A
    head_B -= 1
elif tail_A > 0 and head_B == 0:
    count = count + B_A
    tail_A -= 1

count += min(tail_A, head_B)
print(count)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = [input() for _ in range(N)]
numAB = 0
numinitB = 0
numlastA = 0

for i in s:
    numAB += i.count("AB")
    if i[0] == 'B':
        numinitB += 1
    if i[-1] == 'A':
        numlastA += 1

if numinitB > 0 and numinitB == numlastA:
    print(numAB + numinitB - 1)
elif numinitB == 0 and numlastA == 0:
    print(numAB)
else:
    print(numAB + min(numinitB, numlastA))

Submission status: Wrong Answer

Solution code:
N=int(input())
start=0
end=0
cnt=0
for i in range(N):
    s=input()
    cnt+=s.count('AB')
    if s[0] == 'B':
        start+=1
    if s[-1] == 'A':
        end+=1
print(cnt+min(start,end,N-1))

Submission status: Wrong Answer

Solution code:
x = int(input())
a = 0
b = 0
c = 0
f = 0
bun = []
for p in range(x):
    bun = input()
    if bun[0] == "B":
        b +=1
    if bun[len(bun)-1] == "A":
        a += 1
        if bun[0] == "B":
            f += 1
    for k in range(len(bun)-1):
        if bun[k] == "A":
            if bun[k+1] == "B":
                c += 1




if f == a:
    if a == 0:
        a -= 1
if a < b:
    print(a+c)
else:
    print(b+c)

Submission status: Wrong Answer

Solution code:
from collections import*
n,*s=open(0).read().split()

d=defaultdict(int)
#print(s)
ans=0
for i in s:
    ans+=i.count("AB")
    if i[0]=="B" or i[-1]=="A":
        d[(i[0]=="B",i[-1]=="A")]+=1
#print(d,ans)
if len(d.values())==0:
    print(ans)
else:
    if d[(True,True)]>0 and d[(True,False)]>0 and d[(False,True)]>0:  #ABggfgAB
        ans+=d[(True,True)]+1
        d[(True,True)]=0
        d[(True,False)]-=1 
        d[(False,True)]-=1
#        print(d,ans)
    if d[(True,True)]>0 and d[(True,False)]>0:
#        print(d)
        ans+=d[(True,True)]
        d[(True,True)]=0
        d[(True,False)]-=1
    if d[(True,True)]>0 and d[(False,True)]>0:
#        print(d)
        ans+=d[(True,True)]
        d[(True,True)]=0
        d[(False,True)]-=1
    if d[(True,True)]>1:
        ans+=d[(True,True)]-1
    if d[(False,True)]>0 and d[(True,False)]>0:
#        print(d)
        ans+=min(d[(False,True)],d[(True,False)])
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    N = int(input())
    strings = []
    for i in range(N):
        strings.append(input())
    
    ab = 0
    back_a = 0
    front_b = 0
    back_a_front_b = 0

    for i in strings:
        tmp = i
        ret = tmp.find("AB")
        while ret>=0:
            ab += 1
            tmp = tmp[ret+1:]
            ret = tmp.find("AB")
        
        if i[0] =="B" and i[-1]=="A":
            back_a_front_b += 1
        elif i[0] == "B":
            front_b += 1
        elif i[-1] == "A":
            back_a += 1
    if back_a_front_b == 0:
        print(ab + min([front_b,back_a]))
    elif  min([front_b,back_a]) > 0:
        print(ab + back_a_front_b + 1 + min([front_b-1,back_a-1]))
    else:
        if back_a == 0 and front_b == 0:
            print(ab + min([back_a_front_b -1, 0]))
        else:
            print(ab + back_a_front_b)

    #print("\n" + str(ab))
    #print(back_a_front_b)
    #print(back_a)
    #print(front_b)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
# from sys import exit
N = int(input())
S = [str(input()) for _ in range(N)]
Aend = set()
Bstart = 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)
if len(Bstart) == 1 and len(Aend) == 1 and len(Bstart & Aend) == 1:
    canAB1 = 0
else:
    canAB1 = min(len(Bstart), len(Aend))
print(canAB1 + len(ABcon))

Submission status: Wrong Answer

Solution code:
N = int(input())
b_start = 0
a_end = 0
ok = 0

for i in range(N):
    s = input()
    ok += s.count('AB')
    if s[0] == 'B':
        b_start += 1
    if s[-1] == 'A':
        a_end += 1

print(ok + min(b_start, a_end))

Submission status: Wrong Answer

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

ab_cnt = 0
a_saigo = 0
b_atama = 0
ba_cnt = 0
for s in s_list:
    ab_cnt += s.count("AB")
    if s[0] =="B":
        b_atama += 1
    if s[-1] == "A":
        a_saigo += 1
    if s[0] =="B" and s[-1] == "A":
        ba_cnt += 1

result = ab_cnt + min(b_atama,a_saigo)
if b_atama == ba_cnt and a_saigo == ba_cnt:
    result += -1

print(result)

Submission status: Wrong Answer

Solution code:
N = int(input())
countA = 0
countB = 0
kcount = 0

for i in range(N):
    K = input()
    kcount += K.count("AB")
    K = list(K)
    if K[0] == "B":
        countB += 1 
    if K[-1] == "A":
        countA += 1    
if countB > countA:
    print(kcount+countA)
else:
    print(kcount+countB)

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

for i in range(N):
    if s[i][0]=='B':
        ct_b+=1
    if 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

if ct_b==N:
    ct_b-=1
if ct_a==N:
    ct_a-=1

print(ct_ab+min(ct_a,ct_b))

Submission status: Wrong Answer

Solution code:
# coding: utf-8
def main():
    N = int(input())
    s_i = []
    for _ in range(N):
        s_i.append(input())

    count = 0
    tail_a = 0
    top_b = 0
    both_a_b = 0
    for s in s_i:
        count += s.count("AB")

        if s[-1] == "A":
            if s[0] == "B":
                both_a_b += 1
            else:
                tail_a += 1
        elif s[0] == "B":
            top_b += 1

    #print(count)
    #print(tail_a, top_b, both_a_b)

    if both_a_b > 0:
        count += (both_a_b - 1)

    if tail_a == top_b == 0:
        pass
    elif min(tail_a, top_b) > 0:
        if tail_a == top_b:
            count += tail_a
        else:
            count += min(tail_a, top_b)
            if both_a_b > 0:
                count += 1
    elif min(tail_a, top_b) == 0:
        if both_a_b > 0:
            count += 1

    print(count)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
#https://atcoder.jp/contests/diverta2019/tasks/diverta2019_c

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

flag = False
count = 0
for i in range(len(s)):
    for j in range(len(s[i])):
        if s[i][j] == 'A':
            flag = True
        elif flag == True and s[i][j] == 'B':
            flag = False
            count += 1
        else:
            flag = False

startcnt = [0] * N
endcnt = [0] * N
for i in range(len(s)):
    if s[i][0] == 'B':
        startcnt[i] = 1
    if s[i][len(s[i])-1] == 'A':
        endcnt[i] = 1

cntpls = [0,0,0]
for i in range(N):
    if startcnt[i] + endcnt[i] == 1:
        if startcnt[i] == 1:
            cntpls[0]+= 1
        else:
            cntpls[1] += 1
    elif startcnt[i] + endcnt[i] == 2:
        cntpls[2] += 1

count += min(cntpls[0],cntpls[1]) + min(abs(cntpls[0]-cntpls[1]),cntpls[2])


print(count)

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
for i in range (0,n):
  le=len(li[i])-1
  if li[i][0]=="B":
    sta=sta+1
  if li[i][le]=="A":
    las=las+1
if sta>las:
  print(t+las)
elif sta<las:
  print(t+sta)
elif sta==las==n:
  print(t+n-1)
else:
  print(t+sta)

Submission status: Wrong Answer

Solution code:
N = int(raw_input())

inner_ab_count = 0
f_b_count = 0
l_a_count = 0
b_a_flag = False

for n in xrange(N):
    s = raw_input()
    inner_ab_count += s.count('AB')
    if s[0] == 'B':
        f_b_count += 1
        if s[-1] == 'A':
            b_a_flag = True
            l_a_count += 1
    elif s[-1] == 'A': l_a_count += 1

result = inner_ab_count + min([l_a_count, f_b_count])
if b_a_flag and min([l_a_count, f_b_count]) > 0: result -= 1
print result

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
s = []
ab_num = 0
b_start = 0
a_end = 0
for i in range(N):
    tmp = input()
    s.append(tmp)
    rep = tmp.replace("AB", "")
    ab_num += (len(tmp) - len(rep)) // 2
    if tmp[0] == "B":
        b_start += 1
    if tmp[-1] == "A":
        a_end += 1
if b_start == a_end == N:
    print(ab_num + min(a_end, b_start) - 1)
else:
    print(ab_num + min(a_end, b_start))

Submission status: Wrong Answer

Solution code:
# https://qiita.com/_-_-_-_-_/items/34f933adc7be875e61d0
# abcde	s=input()	s='abcde'
# abcde	s=list(input())	s=['a', 'b', 'c', 'd', 'e']
# 5(1つだけ)	a=int(input())	a=5
# 1 2	| x,y = s_inpl()   |	x=1,y=2
# 1 2 3 4 5 ... n 　	li = input().split()	li=['1','2','3',...,'n']
# 1 2 3 4 5 ... n 　	li = inpl()	li=[1,2,3,4,5,...,n]
# FFFTFTTFF 　	li = input().split('T')	li=['FFF', 'F', '', 'FF']

# INPUT
# 3
# hoge
# foo
# bar
# ANSWER
# n=int(input())
# string_list=[input() for i in range(n)]

import math
import copy
from collections import defaultdict
from collections import Counter
from collections import deque
# 直積 A={a, b, c}, B={d, e}:のとき，A×B={(a,d),(a,e),(b,d),(b,e),(c,d),(c,e)}: product(A, B)
from itertools import product
# 階乗 P!: permutations(seq), 順列 {}_len(seq) P_n: permutations(seq, n)
from itertools import permutations
# 組み合わせ {}_len(seq) C_n: combinations(seq, n)
from itertools import combinations
from bisect import bisect_left, bisect_right
# import numpy as np

def inside(y, x, H, W):
    return 0 <= y < H and 0 <= x < W

# 四方向: 右, 下, 左, 上
dy = [0, -1, 0, 1]
dx = [1, 0, -1, 0]

def i_inpl(): return int(input())
def s_inpl(): return map(int,input().split())
def l_inpl(): return list(map(int, input().split()))
INF = float("inf")

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

ab_cnt = 0
f_a_cnt = 0
f_b_cnt = 0
l_a_cnt = 0
l_b_cnt = 0
for s_i in s:
    ab_cnt += s_i.count("AB")
    if s_i[0] == "A":
        f_a_cnt += 1
    elif s_i[0] == "B":
        f_b_cnt += 1
    if s_i[-1] == "A":
        l_a_cnt += 1
    elif s_i[-1] == "B":
        l_b_cnt += 1

# print(ab_cnt, f_a_cnt, f_b_cnt, l_a_cnt, l_b_cnt)
print(ab_cnt + min(f_a_cnt, l_b_cnt)+ min(f_b_cnt, l_a_cnt))

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:
    if N == 0:
        print(0)
    else:
        print(counter + min([end_a, start_b]) - 1)
else:    
    print(counter + min([end_a, start_b]))

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)) == sum(l4):
    a = min(sum(l2),sum(l3))-1
else:
    a = min(sum(l2),sum(l3))
print(sum(l1) + a)

Submission status: Wrong Answer

Solution code:
ans=0
f_a=0
b_b=0
a_b=0
str_list=[]
N= int(input())
for i in range(N):
    str=input()
    ans=ans+str.count("AB")
    if(str[-1]=="A"):
        f_a=f_a+1
    if(str[0]=="B"):
        b_b=b_b+1
    if(str[-1]=="A"and str[0]=="B"):
        a_b=a_b+1

if(f_a==N and b_b==N):
    ans=ans+N-1
elif((f_a==a_b)and(b_b==a_b)):
    ans=ans+f_a-1
elif(f_a< b_b):
    ans=ans+f_a
else:
    ans=ans+b_b

print(ans)

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
B_start_cnt = 0
A_end_cnt = 0
AB_cnt = 0
BA_cnt = 0
for i in range(N):
    s = input()
    if s[0] == "B" and s[-1] == "A":
        BA_cnt += 1
    if s[0] == "B":
        B_start_cnt += 1
    if s[-1] == "A":
        A_end_cnt += 1
    AB_cnt += s.count('AB')
ans = min(A_end_cnt,B_start_cnt)+AB_cnt
if A_end_cnt == BA_cnt and B_start_cnt == BA_cnt:
    ans -= 1
print(ans)

Submission status: Wrong Answer

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

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

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

flag = False
if d > 0:
    flag = True
    res += d // 2
    if d%2 == 1:
        d = 1
    else:
        d = 0
        
if d == 1 and max(t, l) - min(t, l) > 0:
    res += min(2, max(t, l) - min(t, l))
   
if flag and d == 0 and max(t, l) - min(t, l) > 0:
    res += 1

    
print(res)

Submission status: Wrong Answer

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


def solve(N: int, s: "List[str]"):
    count_AB = 0
    count_endswith_A = 0
    count_startswith_B = 0
    count_BA = 0
    for ss in s:
        count_AB += ss.count('AB')
        if ss.endswith('A') and ss.startswith('B'):
            count_BA += 1
            continue
        if ss.endswith('A'):
            count_endswith_A += 1
        if ss.startswith('B'):
            count_startswith_B += 1
    count_pair = min(count_endswith_A, count_startswith_B)
    if count_pair > 0:
        print(count_AB + count_pair + count_BA)
    elif count_endswith_A > 0 or count_startswith_B > 0:
        print(count_AB + count_BA)
    else:
        print(count_AB + count_BA - 1)
    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: Wrong Answer

Solution code:
n = input()
N = int(n)

count = 0
Acount = 0
Bcount = 0
BAcount = 0

for i in range(N):
    s = input()
    if 1 < len(s):
        if 'AB' in s:
            count += 1
        if s[0] == 'B' and s[-1] == 'A':
            BAcount += 1
        elif s[0] == 'B':
            Bcount += 1
        elif s[-1] == 'A':
            Acount += 1
    else:
        if s == 'B':
            Bcount += 1
        if s == 'A':
            Acount += 1
count += min(Bcount, Acount)
BorA = abs(Bcount - Acount)

tmp = BorA + BAcount - 1
if 0 < tmp:
    count += tmp

print(count)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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



def main(s):
    SB = [si for si in s if si[0] == 'B']
    SR = [si for si in s if si[0] != 'B']
    if SR:
        R = [SR.pop()]
    else:
        R = [SB.pop()]
    while SR or SB:
        if SR and SB:
            if R[-1][-1] == 'A':
                R.append(SB.pop())
            else:
                R.append(SR.pop())
        elif SR:
            R.append(SR.pop())
        elif SB:
            R.append(SB.pop())
    return "".join(R).count("AB")


print(main(s))

Submission status: Wrong Answer

Solution code:
def input_from_console():
    n = int(input())
    s_list = []
    for i in range(n):
        s_list.append(input())
    return n, s_list


def count_ab_in_string(s_list):
    return sum([item.count('AB') for item in s_list])


def count_start_with_b(s_list):
    return sum([1 if item.startswith('B') else 0 for item in s_list])


def count_end_with_a(s_list):
    return sum([1 if item.endswith('A') else 0 for item in s_list])


def main():
    n, s_list = input_from_console()
    contains_count = count_ab_in_string(s_list)
    connect_count = min(count_start_with_b(s_list), count_end_with_a(s_list))
    print(contains_count + connect_count)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def main():
    from sys import stdin, stdout

    def read():
        return stdin.readline().rstrip('\n')

    def read_array(sep=None, maxsplit=-1):
        return read().split(sep, maxsplit)

    def read_int():
        return int(read())

    def read_int_array(sep=None, maxsplit=-1):
        return [int(a) for a in read_array(sep, maxsplit)]

    def write(*args, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in args) + end)

    def write_array(array, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in array) + end)

    n = read_int()
    b_starts = 0
    a_ends = 0
    both = 0
    count = 0

    for i in range(n):
        word = read().strip()
        for i in range(1, len(word)):
            if word[i-1] == 'A' and word[i] == 'B':
                count += 1

        if word[0] == 'B' and word[-1] == 'A':
            both += 1
        elif word[-1] == 'A':
            a_ends += 1
        elif word[0] == 'B':
            b_starts += 1

    if a_ends > 0 and b_starts > 0:
        count += both + 1
        a_ends -= 1
        b_starts -= 1
    elif a_ends > 0:
        count += both
        a_ends -= 1
    elif b_starts > 0:
        count += both
        b_starts -= 1
    else:
        count += both - 1
    count += min(a_ends, b_starts)

    write(count)

main()

Submission status: Wrong Answer

Solution code:
N = int(input())

a = 0
b = 0
ans = 0

for _ in range(N):
    s = input()
    flag = False
    for i in range(len(s)):
        if (flag == True) and (s[i] == "B"):
            ans += 1
            flag = False
        elif (flag == False) and (s[i] == "A"):
            flag = True
        elif (flag == True):
            flag = False
        if (i == 0) and (s[i] == "B"):
            b += 1
        if (i == len(s)-1) and (s[i] == "A"):
            a += 1
print(ans + min(a, b))

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

total = 0

for _ in range(N):

    s = input()

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

    total += s.count('AB')

additional = min(head_b_count, tail_a_count)

if additional == N:
    additional -= 1

total += additional

print(total)

Submission status: Wrong Answer

Solution code:
#
import itertools
from collections import Counter
from collections import defaultdict
import bisect

def main():
    N = int(input())
    inside = 0

    top_B = 0
    tail_A = 0
    both = 0
    for _ in range(N):
        s = input()
        inside += s.count('AB')
        if s[0] == 'B' and s[-1] == 'A':
            both += 1
        else:
            if s[0] == 'B':
                top_B += 1
            elif s[-1] == 'A':
                tail_A += 1
    # print('inside = {}, top b = {}, tail a = {}, both = {}'.format(inside, top_B, tail_A, both))
    ans = inside

    if both > 0:
        if tail_A == 0:
            tail_A += 1
            both -= 1
        if top_B == 0 and both > 0:
            top_B += 1
            both -= 1

    while both > 0 and top_B > 0 and tail_A > 0:
        ans += 2
        both -= 1
        tail_A -= 1
        top_B -= 1

        if both > 0:
            if tail_A == 0:
                tail_A += 1
                both -= 1
            elif top_B == 0:
                top_B += 1
                both -= 1

    ans += min(top_B, tail_A)

    print(ans)


if __name__ == '__main__':
    main()