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:
#!/usr/bin/env python
# -*- coding: utf-8 -*-


def main():
  lines = [input().strip() for _ in range(int(input()))]
  types = [(int(s[0] == 'B'), int(s[-1] == 'A')) for s in lines]
  count = sum(s.count('AB') for s in lines)

  before = sum(t[0] for t in types)
  after = sum(t[1] for t in types)

  if (0, 1) not in types:
    before -= 1

  if (1, 0) not in types:
    after -= 1

  print(count + min(before, after))


if __name__ == '__main__':
  main()

Submission status: Wrong Answer

Solution code:
N = int(input())
a = 0
b = 0
c = 0
v = 0

for i in range(N):
    S = input()
    for j in range(len(S)-1):
        if S[j:j+2] == 'AB':
            c += 1
    if S[0] == 'B' and S[-1] == 'A':
        v += 1
        continue
    if S[0] == 'B':
        b += 1
    if S[-1] == 'A':
        a += 1

if v >= 1:
    if a < b:
        a += 1
    else:
        b += 1
    
v = max(0, v-1)
print(c + v + min(a, b))

Submission status: Wrong Answer

Solution code:
n = int(input())
a = 0
b = 0
c = 0
ab = 0
ba = 0

for i in range(n):
    s = input()
    ab += s.count('AB')

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

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

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

if 0 < ba:
    ba -= 1

if a != b and 0 < ba:
    c = 1

print(ab + min(a, b) + ba + c)

Submission status: Wrong Answer

Solution code:
n = int(input())

d= 0
e = {'A' : 0, 'B' : 0, 'A_double': 0}
for i in range(n):
    S = input().strip()
    d += S.count('AB')
    if (S[0] == 'A' or S[-1] == 'A'): 
        e['A'] += 1
    if len(S) == 1 and S[0] == 'A':
        e['A'] += 1
    if S[0] == 'B' or S[-1] == 'B':
        e['B']+=1
    if len(S) == 1 and S[0] == 'B':
        e['B'] += 1

d+= min(e.values())
print(d)

Submission status: Wrong Answer

Solution code:
# N < 10000
N = int(input())

# len(s) < 10

count = 0
a, b, ba = 0, 0, 0
for i in range(N):
    s = input().rstrip()
    count += s.count("AB")

    if s[-1] == 'A':
        if s[0] == 'B':
            ba += 1
        else:
            a += 1
    elif s[0] == 'B':
        b += 1

#e = int(input())
#print("*A=",a, ", B*=",b, "B*A=",ba, ",AB=", count, ",expected=", e)

if ba > 1:
    count += ba - 1
    ba = 1
count+=max(min(a+ba,b),min(a,b+ba))
print(count)

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:
def ab_substrings(N: int, S: list)->int:
    res = 0
    endA = 0
    startB = 0

    for s in S:
        res += s.count('AB')
        endA += s.endswith('A')
        startB += s.startswith('B')

    for s in S:
        if s.endswith('A') and endA > 0:
            if not s.startswith('B') and startB > 0:
                res += 1
                endA -= 1
                startB -= 1
            if s.startswith('B') and startB > 1:
                res += 1
                endA -= 1
                startB -= 1

    return res


if __name__ == "__main__":
    N = int(input())
    S = [input() for _ in range(N)]

    ans = ab_substrings(N, S)
    print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
S = []
for i in range(n):
    s = str(input())
    S.append(s)
    
ans = 0
countA = 0
countB = 0
countBA = 0
for s in S:
    if s[0] == 'B' and s[len(s)-1] == 'A':
        countBA += 1
        
    elif s[len(s)-1] == 'A':
        countA += 1
        
    elif s[0] == 'B':
        countB += 1
        
    for i in range(len(s) - 1):
        if s[i] == 'A' and s[i+1] == 'B':
            ans += 1
            
if countA > countB:
    ans += countB
    countA -= countB
    
    if countA > countBA:
        ans += countBA
        
    else:
        ans += countA
        countBA -= countA
        ans += countBA // 2
        
else:
    ans += countA
    countB -= countA
    
    if countB > countBA:
        ans += countBA
        
    else:
        ans += countB
        countBA -= countB
        ans += countBA // 2
        
print(ans)

Submission status: Wrong Answer

Solution code:
count = 0
sta_a, sta_b, en_a, en_b = 0, 0, 0, 0
dab, dba = 0,0
n = int(input())
for _ in range(n):
  flag = True
  l = list(input())
  for i in range(len(l)-1):
    if l[i] == 'A':
      if l[i+1] == 'B':
        count += 1
  if l[0] == 'A' and l[-1] == 'B':
    dab += 1
    flag = False
  elif l[0] == 'B' and l[-1] == 'A':
    dba += 1
    flag = False
  if l[0] == 'A' and flag:
    sta_a += 1
  if l[0] == 'B' and flag:
    sta_b += 1
  if l[-1] == 'A' and flag:
    en_a += 1
  if l[-1] == 'B' and flag:
    en_b += 1

if dab > 1:
  count += dab-1
  dab = 1
if dba > 1:
  count += dba-1
  dba = 1

li = [sta_a, sta_b, en_a, en_b]
c1 = min(sta_a, en_b)
c2 = min(sta_b, en_a)
count += c1 + c2
sta_a -= c1
sta_b -= c2
en_b -= c1
en_a -= c2
li = [sta_a, sta_b, en_a, en_b]
if (sta_b > 0 and dba > 0) or (en_a > 0 and dba > 0):
  count += 1
elif (sta_a > 0 and dab > 0) or (en_b > 0 and dba > 0):
  count += 1
li = [sta_a, sta_b, en_a, en_b]
print(count)

Submission status: Wrong Answer

Solution code:
N = int(input())
a = [input() for i in range(N)]
b = 0
c = 0
d = 0
e = 0
for j in range(N):
    for k in range(len(a[j]) - 1):
        if a[j][k] == "A" and a[j][k + 1] == "B":
            b += 1
    if a[j][len(a[j])- 1] == "A":
        c += 1
    if a[j][0] == "B":
        d += 1
    if a[j][len(a[j])-1] == "A" and a[j][0] == "B":
      e = 1
if c == 1 and d == 1 and e == 1:
  print(b)
else:
  f = min(c, d)
  print(b + f)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for i in range(n)]
count = 0
count_a = 0
count_b = 0
count_ab = 0
for i in range(n):
    count += s[i].count("AB")
    if s[i][-1] == "A" and s[i][0] != "B":
        count_a += 1
    if s[i][0] == "B" and s[i][-1] != "A":
        count_b += 1
    if s[i][0] == "B" and s[i][-1] == "A":
        count_ab += 1

# print([count,count_a,count_b,count_ab])

if n == 1:
    print(count)
else:
    print(count+min([count_a,count_b])+count_ab)

Submission status: Wrong Answer

Solution code:
n=int(input())
s=[input() for i in range(n)]
ans=sum([s[i].count("AB") for i in range(n)])
a=[s[i].count("AB") for i in range(n)]
xxA=sum([1 if s[i][0]!="B" and s[i][-1]=="A"else 0 for i in range(n)])
Bxx=sum([1 if s[i][0]=="B" and s[i][-1]!="A" else 0 for i in range(n)])
BxA=sum([1 if s[i][0]=="B" and s[i][-1]=="A" else 0 for i in range(n)])
if (abs(xxA-Bxx))>BxA:
    wer=min(xxA,Bxx)+min(abs(xxA-Bxx),BxA)
else:
    wer=min(xxA,Bxx)+BxA
print(ans+wer)

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

p = min([ba, min([a, b])])
ab += 2*p
ba -= p
a -= p
b -= p

if ba == 0:
    ab += min([a, b])
else:
    ab += ba - 1
    if a > 0 or b > 0:
        ab += 1

print(ab)

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)
        
a = len(g1)
b = len(g2)
c = len(g3)

if a == b:
    cnt += a
    if c > 1:
        cnt += c - 1
elif a > b:
    cnt += b
    cnt += c
elif b > a:
    cnt += a
    cnt += c

print(cnt)

Submission status: Wrong Answer

Solution code:
N = int(input())
topb = 0
taila = 0
both = 0
cnt = 0
for _ in range(N):
    s = input()
    cnt +=s.count("AB")

    if s[0] == "B" and s[-1] == "A":
        both += 1
    elif s[0] == "B":
        topb += 1
    elif s[-1] == "A":
        taila += 1

con_cnt_min,con_cnt_max = min(topb,taila),max(topb,taila)
con_cnt = min(con_cnt_min+both,con_cnt_max)
left_both = con_cnt - con_cnt_min

if left_both >=1:
    cnt += left_both
print(cnt + con_cnt)

Submission status: Wrong Answer

Solution code:
import sys
import re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits



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


def INT(): return int(input())


def MAP(): return map(int, input().split())


def LIST(): return list(map(int, input().split()))



sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

n = INT()
s = [input() for _ in range(n)]

lis1 = []
lis2 = []
lis3 = []
lis4 = []

for x in s:
    if (x[0] == 'B' and x[-1] == 'A'):
        lis1.append(x)
        
    if (x[-1] == 'A' and x not in lis1):
        lis2.append(x)

    if (x[0] == 'B' and x not in lis1):
        lis3.append(x)
        
for x in s:
    if 'AB' in x and x not in lis1 and x not in lis2 and x not in lis3:
        lis4.append(x)

#print(lis1)
#print(lis2)
#print(lis3)
#print(lis4)

ct = 0
for x in lis1:
    ct += x.count('AB')
for x in lis2:
    ct += x.count('AB')
for x in lis3:
    ct += x.count('AB')
for x in lis4:
    ct += x.count('AB')


if lis2 == [] and lis3 != []:
    p = min(len(lis1), len(lis3))

    #print(ct,p)

    print(ct + p)

elif lis2 == [] and lis3 == []:
    print(max(len(lis1) - 1,0) + ct)

else :        
    p = min(len(lis2), len(lis3))
    q = len(lis1)

    #print(ct,p,q)

    print(ct + p + q)

Submission status: Wrong Answer

Solution code:
n=int(input())
god=[]
F=0
B=0
both=0
cnt=0
s=([input() for i in range(n)])
for i in range(n):
	cnt+=s[i].count('AB')
	if s[i][0]=='B' and s[i][len(s[i])-1]=='A':
		both+=1
	elif s[i][0]=='B':
		F+=1
	elif s[i][len(s[i])-1]=='A':
		B+=1
#print(both)
#print(F)
#print(B)
#print(cnt)
cnt+=min(F,B)
if both<=abs(F-B):
	cnt+=both
elif abs(F-B)<both:
	cnt+=abs(F-B)+int((both-abs(F-B))/2)+1
print(cnt)

Submission status: Wrong Answer

Solution code:
n=int(input())
count=0
dual=0
startb=0
enda=0

f1=0
f2=0

for i in range(n):
    tmp=list(input())
    if tmp[0]=="B" and tmp[-1]=="A":
        #dual+=1
        startb+=1
        enda+=1
    elif tmp[0]=="B":
        startb+=1
        f1+=1
    elif tmp[-1]=="A":
        enda+=1
        f2+=1

    aflag=0
    for t in tmp:
        if aflag==1 and t=="B":
            count+=1
            aflag=0
        elif t=="A":
            aflag=1
        else:
            aflag=0
"""
while dual>0:
    if startb>enda:
        enda+=1
    else:
        startb+=1
    dual-=1
"""
count+=min(startb,enda)

#補正
if f1 ==0 and f2==0:
    count-=1
if count<0:
    count=0

print(count)

Submission status: Wrong Answer

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

firstB=0
endA=0
feAB=0
AB=0
for i in listA:
    AB+=len(re.findall("AB",i))
    
    if i[0]=="B":
        firstB+=1
    if i[-1]=="A":
        endA+=1
        if i[0]=="B":
            feAB+=1
AB+=min([endA,firstB])
print(AB)

Submission status: Wrong Answer

Solution code:
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math

mod = 10**9+7

N = int(input())
s = [0 for i in range(N)]
cnt = 0
chance = False
A_cnt = 0
B_cnt = 0
BA_cnt = 0
for i in range(N):
    s[i] = str(input())
    cnt += s[i].count("AB")
    if s[i][0] == "B" and s[i][-1]=="A":
        BA_cnt += 1
    elif s[i][0] == "B":
        B_cnt += 1
    elif s[i][-1] == "A":
        A_cnt += 1


if BA_cnt != 0 and A_cnt == 0:
    plus = BA_cnt-1
else:
    plus = min(BA_cnt+A_cnt,BA_cnt+B_cnt)

cnt += plus

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

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())
s = [input() for i in range(n)]
count,a,b,ab = 0,0,0,0
for word in s:
  while "AB" in word:
    count += 1
    word = word.replace("AB","")
  if word[0] == "B" and word[-1] =="A":
    ab += 1
  elif word[0] == "B":
    b += 1
  elif word[-1] == "A":
    a += 1
  else:
    pass
if a == b and ab != 0:
  ab -= 1
print(min([a,b])+ab+count)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
count = 0
boa = 0
boo = 0
ooa = 0
for _ in range(n):
  i = input()
  s += [i]
  l = len(i)
  for k in range(l-1):
    if i[k:k+2] == 'AB':
      count += 1
  if i[0] == 'B' and i[-1] == 'A':
    boa += 1
  elif i[0] == 'B':
    boo += 1
  elif i[-1] == 'A':
    ooa += 1
count += boa
count += min(boo,ooa)
print(count)

Submission status: Wrong Answer

Solution code:
N=int(input())
A_list=0
B_list=0
both=0
count=0
for i in range(0,N):
    txt=input()
    if "AB" in txt:
        count+=1
    
    if(txt[0]=="B" and txt[-1]=="A"):
        both+=1
    elif (txt[0]=="B"):
        B_list+=1
    elif(txt[-1]=="A"):
        A_list+=1
if (both>0):
    count+=(both-1)
index=min(A_list,B_list)
count+=index
if(A_list!=B_list and both>0):
    count+=1
print(count)

Submission status: Wrong Answer

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

cnt = 0
for i in range(n):
    cnt += s[i].count("AB")
cnt_a = 0
cnt_b = 0
cnt_ab = 0
for i in range(n):
    len_s = len(s[i])
    if s[i][len_s - 1] == "A":
        cnt_a += 1
    if s[i][0] == "B":
        cnt_b += 1
    if s[i][0] == "B" and s[i][len_s - 1] == "A":
        cnt_ab += 1
if cnt_a == cnt_ab and cnt_a > 0:
    print(cnt + min(cnt_a, cnt_b) - 1)
else:
    print(cnt + min(cnt_a, cnt_b))

Submission status: Wrong Answer

Solution code:
n=int(input())
s=[]
for i in range(n):
  s.append(input())
cnt_a=0
cnt_b=0
cnt_ab=0
for j in range(n):
  if s[j][0]=='B' and s[j][len(s[j])-1]=='A':
    cnt_ab+=1
  elif s[j][0]=='B':
    cnt_b+=1
  elif s[j][len(s[j])-1]=='A':
    cnt_a+=1
cnt_a+=cnt_ab
cnt_b+=cnt_ab
cnt_2=0
for l in range(n):
  cnt_2+=s[l].count('AB')
if cnt_ab==n:
  print(n+cnt_2-1)
elif cnt_ab==1 and cnt_a==1 and cnt_b==1:
  print(cnt_2)
else:
  print(min(cnt_a,cnt_b)+cnt_2)

Submission status: Wrong Answer

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

    ans += si.count("AB")




d = {}
d["A"] = 0
d["B"] = 0
d["all"] = 0

for i in range(N):
    if s[i][0] == "B" and s[i][-1] == "A":
        d["all"] += 1
    elif s[i][0] == "B":
        d["B"] += 1
    elif s[i][-1] == "A":
        d["A"] += 1


c = min(d["A"],d["B"],d["all"])
ans += (c*2)
d["A"] -= c
d["B"] -= c
d["all"] -= c

if d["all"] == 0:
    ans += min(d["A"],d["B"])
elif d["A"] == 0 and d["B"] == 0:
    ans += d["all"] // 2
elif d["A"] == 0:
    if d["B"] >= d["all"]*2:
        ans += 2*min(d["all"]//2,d["B"])
    else:
        ans += 2*min(d["all"]//2,d["B"])
        d["all"] -= 2*min(d["all"]//2,d["B"])
        ans += d["all"] // 2

elif d["B"] == 0:
    if d["A"] >= d["all"]*2:
        ans += 2*min(d["all"]//2,d["A"])
    else:
        ans += 2*min(d["all"]//2,d["A"])
        d["all"] -= 2*min(d["all"]//2,d["A"])
        ans += d["all"] // 2



print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
N = int(input())
S = []
for i in range(N):
    S.append(str(input()))
    
start_b = 0
end_a = 0
ab_count = 0
for i in S:
    if i[0]=="B":
        start_b = start_b + 1
    if i[-1]=="A":
        end_a = end_a + 1
    ab_count = ab_count + i.count("AB")

additional = min(start_b, end_a)
if additional == len(S):
    additional = additional  - 1
ans = ab_count + additional
print(ans)

Submission status: Wrong Answer

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


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

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


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

    print(ans1+ans2)
    
    return


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

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
si = [input() for _ in range(N)]
count = 0
A_ = 0
B_ = 0
for s in si:
    if s[-1] =="A":
        A_ +=1
    if s[0] =="B":
        B_ +=1
    for i in range(len(s)-1):
        if s[i] =="A" and s[i+1] == "B":
            count += 1
count += min(A_, B_)       

print(count)

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]:
    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())
S =[0]*N
for i in range(N):
    S[i] = str(input())

ans = int(0)
a=int(0)
b=int(0)

for i in range(N):
    if 'AB' in S[i]: ans +=1
    if S[i].endswith('A'): a +=1
    if S[i].startswith('B'): b +=1

R = min(a,b)

ans += R

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
eni_B = 0
end_A = 0
both = 0
count = 0

for i in range(N):
    s = list(input())
    if s[0] == 'B':
        eni_B += 1
    if s[-1] == 'A':
        end_A += 1
    if s[0] == 'B' and s[-1] == 'A':
        eni_B -= 1
        end_A -= 1
        both += 1
    for j in range(len(s)-1):
        if s[j] == 'A':
            if s[j+1] == 'B':
                count += 1


m = min(end_A,eni_B)
M = max(end_A,eni_B)

count = count + m 

if M - m == 0 :
    count = count + both - 1
else:
    count = count + both

print(count)

Submission status: Wrong Answer

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

count=0
ca=0
cb=0
for i in range(N):
    if S[i][0]=="B":
        ca+=1
    if S[i][len(S[i])-1]=="A":
        cb+=1
    for x in range(len(S[i])-1):
        if S[i][x:x+2]=="AB":
            count+=1
print(count+min(ca,cb,N-1))

Submission status: Wrong Answer

Solution code:
N = int(input())
a = [str(input()) for i in range(N)]
cnt = 0
yobiflag = 0
bflag = 0
aflag = 0
for i in range(N):
    flag = False
    if a[i][0] == "B":
        if a[i][-1] == "A":
            yobiflag += 1
            bflag += 1
            aflag += 1
        else:
            bflag += 1
    else:
        if a[i][-1] == "A":
            aflag += 1

    for j in range(len(a[i])):
        # print(a[i][j])
        if a[i][j] == "B" and flag:
            cnt += 1
        flag = False

        if a[i][j] == "A":
            flag = True

if yobiflag == N:
    bflag = yobiflag - 1
if yobiflag ==N:
    aflag = yobiflag - 1
# print(yobiflag)
# print(cnt)
# print(aflag)
# print(bflag)
print(cnt + min(aflag, bflag, ))

Submission status: Wrong Answer

Solution code:
N = int(input())
ls = []
subst = 0
suba = 0
subb = 0
for i in range(N):
    temp = input()
    subst += temp.count('AB')
    if temp[0] == 'B':
        suba += 1
    if temp[-1] == 'A':
        subb += 1
print(subst+min(subb,suba))

Submission status: Wrong Answer

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

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

if 1 < ab:
	ab -= 1

print(abc + min(aend + ab, bbeg + ab))

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 += c - 1 + bool(a or b)

    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:
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
            if tail_A > 0:
                AB_count += 1
                tail_A -= 1
            else:
                head_B += 1
        elif list(si)[-1] == 'A':
            tail_A_count += 1
            if head_B > 0:
                AB_count += 1
                head_B -= 1
            else:
                tail_A += 1
    if B_and_A_count > 0:
        AB_count += B_and_A_count - 1
        if head_B > 0:
            AB_count += 1
        if tail_A > 0:
            AB_count += 1
    print(AB_count)


if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

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

S = [input() for _ in range(int(input()))]

AB = 0
end_A = 0
start_B = 0
sB_eA = 0

for s in S:
    AB += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        sB_eA += 1
    elif s[0] == 'B':
        start_B += 1
    elif s[-1] == 'A':
        end_A += 1
amari = abs(start_B-end_A)
last = abs(amari-sB_eA)
print(AB+min(start_B,end_A)+min(amari,sB_eA)+last//2)

Submission status: Wrong Answer

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

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

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

        if a > b:
            cnt += a//b + ab
        else:
            cnt += b//a + ab

print(cnt)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
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
# f1: B....X
# f2: X....A
# f3: B....A
if f1 == 0:
    ans += min(f2, f3)
    if f2 == 0:
        ans += max(0, f3-1)
    else:
        t = min(f2, f3)
        f2 -= t
        f3 -= t
        ans += f3

elif f2 == 0:
    if f1 == 0:
        ans += max(0, f3-1)
    else:
        if f3 == 0:
            pass
        else:
            t = min(f1, f3)
            ans += t
            f1 -= t
            f3 -= t

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())
A_list=0
B_list=0
both=0
count=0
for i in range(0,N):
    txt=input()
    if "AB" in txt:
        count+=1
    
    if(txt[0]=="B" and txt[-1]=="A"):
        both+=1
    elif (txt[0]=="B"):
        B_list+=1
    elif(txt[-1]=="A"):
        A_list+=1
if (both>1):
    count+=(both-1)
index=min(A_list,B_list)
count+=index
if(A_list!=B_list):
    count+=1
print(count)

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
        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())
ans = 0
A = 0
B = 0
for i in range(N):
  s = input()
  ans += s.count('AB')
  if s[len(s)-1] == 'A':
    A+=1
  if s[0] == 'B':
    B+=1
if A!=0 and B!=0 and (A!=N and B!=N):
  if A>B:
    print(ans+B)
  else:
    print(ans+A)
else:
  if A==N and B==N:
    print(ans+int((A+B)/2)-1)
  else:
    print(ans)

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 abs(a_cnt-b_cnt)==0 and ab_cnt > 0:
    ab_cnt += 1
    
#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[ ]: