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 random
#
# dist = ["#","."]
#
# f = open("in_sample.txt","w")
#
# f.write("1000 1000\n")
#
# for i in range(1000):
#     temp =[]
#     for j in range(1000):
#         temp.append(random.choice(dist))
#     f.writelines(temp)
#     f.write("\n")


n = int(input())
count = 0
enda = 0
startb = 0
for i in range(n):
    s = input()
    flag = False
    for i in range(len(s)):
        if flag and s[i] == "B":
            count += 1
            flag = False
        else:
            flag = False
        if s[i] == "A":
            flag = True
    if s[0] == "B":
        startb += 1
    if s[-1] == "A":
        enda += 1
print(count + min(startb,enda))

Submission status: Wrong Answer

Solution code:
n = int(input())
c= 0
x=0
y=0
z=0
for i in range(n):
    s = input()
    c += s.count('AB')
    
    if s[-1]=='A' and s[0]=='B':
        x+=1
    elif s[0]=='B':
        y+=1
    elif s[-1]=='A':
        z+=1

if y>=0 or z>=0:
    c += x
c += min(y,z)
print(c)

Submission status: Wrong Answer

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

num_ab = 0
pres = []
posts = []
ss2 = []
for s in ss:
    while True:
        if len(s) > 1:
            if s[0:2] == 'AB':
                s = s[2:]
                num_ab += 1
            else:
                break
    while True:
        if len(s) > 1:
            if s[-2:] == 'AB':
                s = s[:-2]
                num_ab += 1
            else:
                break
#     print(s)
    if s[0] == 'A':
        pres.append(1)
    elif s[0] == 'B':
        pres.append(-1)
    else:
        pres.append(0)
    if s[-1] == 'A':
        posts.append(1)
    elif s[-1] == 'B':
        posts.append(-1)
    else:
        posts.append(0)
        
    ss2.append(s)

pre_num = np.sum(np.array(pres) == -1) 
post_num = np.sum(np.array(posts) == 1)
num_ab += np.min([pre_num, post_num])

pre_num = np.sum(np.array(pres) == 1) 
post_num = np.sum(np.array(posts) == -1)
num_ab += np.min([pre_num, post_num])

for s in ss2:
    while True:
        i = s.find('AB')
        if i > 0:
            num_ab += 1
            s = s[i + 2:]
        else:
            break
        
print(num_ab)

Submission status: Wrong Answer

Solution code:
n = int(input())
ab = 0
frontb = 0
backa = 0
count = 0
ryou = 0
for i in range(n):
    s = input()
    for j in range(len(s)-1):
        if s[j] == 'A' and s[j+1] == 'B':
            count += 1
    if s[0] == 'B' and s[-1] == 'A':ryou += 1
    if s[0] == 'B':frontb += 1
    if s[-1] == 'A':backa += 1
if frontb + backa == ryou*2:
    count += backa-1
else:
    count += min(backa,frontb)
print(count)

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
if numb >= numa:
    ans += numa
    rem = numb - numa
else:
    ans += numb
    rem = numa - numb
if rem > 0:
    ans += numba
else:
    ans += max(0, numba - 1)
print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n = int(input())
fully_ab = 0
last_a = 0
head_b = 0
head_last_both = 0

for i in range(n):
    s = input().rstrip()
    fully_ab +=s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        head_last_both += 1
    elif s[0] == "B":
        head_b += 1
    elif s[-1] == "A":
        last_a += 1
    

bigger = max(last_a,head_b)
lower  = min(last_a,head_b)
amari = bigger - lower

connected = max(0,head_last_both - 1)

ans = fully_ab + lower + connected

if amari > 0 and head_last_both > 0:
    ans += 1
print(ans)

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

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

    inner = 0
    for s in S:
        inner += s.count("AB")
    
    B_ended = 0
    A_begin = 0

    A_ended = 0
    B_begin = 0
    both = 0
    for s in S:
        if s[0] == "B" and s[-1] == "A":
            both += 1   

        elif s[0] == "B": B_begin += 1
        elif s[-1] == "A": A_ended += 1

    
    mmA = min(A_ended, B_begin)    

    if A_ended != B_begin:
        # 片方余ってるとき
        mmA += both
    elif both > 0:
        mmA += both - 1 
    
    print(inner + mmA )
    

if __name__ == "__main__":
    solve()

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

a = max(a,b)
b = max(a,b)
sa = (a-b)//2
if sa > ab:
    a -= ab
    b += ab
    ab = 0
    ans += ab
    ans += min(a,b)
else:
    a -= sa
    b += sa
    ab -= sa
    ans += sa
    ans += min(a,b)
    if ab != 0:
        ans += ab-1
        ans += 1 if abs(a-b) else 0

print(ans)

Submission status: Wrong Answer

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

head_a_num = 0
tail_b_num = 0
both_num = 0
cnt = 0
for i in s:
  if i[0] == 'B':
    tail_b_num += 1
  if i[-1] == 'A':
    head_a_num += 1
  if i[0] == 'B' and i[-1] == 'A':
    both_num += 1
  cnt += i.count('AB')

cnt += both_num - 1
tail_b_num -= both_num
head_a_num -= both_num
if tail_b_num > 0:
  cnt += 1
  tail_b_num -= 1
if head_a_num > 0:
  cnt += 1
  head_a_num -= 1

cnt += min(tail_b_num,head_a_num)
  
print(cnt)

Submission status: Wrong Answer

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

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

ans = sum([s.count('AB') for s in S])
count_A = 0
count_B = 0
count_AB = 0
for s in S:
    if s[0] == 'B':
        count_A += 1
        if s[-1] == 'A':
            count_B += 1
    if s[-1] == 'A':
        count_B += 1

if max(count_A, count_B) == count_AB:
    ans += count_AB-1
else:
    ans += min(count_A, count_B)

print(ans)

Submission status: Wrong Answer

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

bstart, aend = 0, 0
doubleend = 0
ab = 0
for item in s:
    if item[0] == "B" and item[-1] == "A":
        doubleend += 1
    else:
        if item[-1] == "A":
            aend += 1
        if item[0] == "B":
            bstart += 1
    ab += item.count("AB")

ab += max(doubleend - 1, 0)
n -= (doubleend - 1)
if bstart > 0:
    ab += 1
    bstart -= 1
    n -= 1
if aend > 0:
    ab += 1
    aend -= 1
    n -= 1
ab += min(aend, bstart, n-1) 
print(ab)

Submission status: Wrong Answer

Solution code:
N = int(input())

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

print(count + min([a, b, N - 1]))
#print(a, b)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!

n = int(input())

words=[input() for i in range(n)]

cnt=0

for i,word in enumerate(words):
    for j in range(len(word)-1):
        if word[j:j+2]=="AB":
            cnt+=1

cntB=0
cntA=0
for word in words:
    if word[0]=="B":
        cntB += 1
    if word[-1]=="A":
        cntA += 1
print(min(cntA,cntB)+cnt)

Submission status: Wrong Answer

Solution code:
n = int(input())
ans = 0
last_a = 0
start_b = 0
for i in range(n):
    s = input()
    ans += s.count("AB")
    if s.rfind("A") == len(s) - 1:
        last_a += 1
    if s.find("B") == 0:
        start_b += 1
ans += min(last_a, start_b)
print(ans)

Submission status: Wrong Answer

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

N = int(input())
S = [input() for _ in range(N)]
l, m, n = 0, 0, 0
ans = 0
for s in S:
    if s[0] == 'B' and s[-2] == 'A':
        n += 1
    elif s[0] == 'B':
        m += 1
    elif s[-2] == 'A':
        l += 1
    for i in range(len(s)-1):
        if s[i:i+2] == 'AB':
            ans += 1
ans += min(l, m)
if n > 0:
    ans += n - 1
if l != m:
    ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
N=int(input())
s=' '
num_AB=0
num_A=0
num_B=0
for i in range(0,N):
    s=str(input())
    if("AB" in s):
        num_AB+=1
    if(s[0]=='B'):
        num_B+=1
    if(s[-1]=='A'):
        num_A+=1
ans=num_AB+min(num_A,num_B)
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = 0
t = 0
u = 0
v = 0
for i in range(N):
    m = input()
    u += m.count("AB")
    if m[0] == "B" and m[-1] == "A":
        v += 1
    else:
        if m[0] == "B":
            s += 1
        if m[-1] == "A":
            t += 1
if s == 0 and t == 0:
    u += v - 1
    print(u)
elif s == 0 or t == 0:
    u += v
    print(u)
else: 
    u += min(s, t) + v
    print(u)

Submission status: Wrong Answer

Solution code:
n = int(input())
cnt = 0
startb = 0
enda = 0
both = 0
S = []
for i in range(n):
    s = input()
    S.append(s)
    cnt += s.count('AB')
    if s[0] == 'B':
        startb += 1
    if s[-1] == 'A':
        enda += 1
    if s[0] == 'B' and s[-1] == 'A':
        both += 1
if both == startb == enda:
    print(cnt+both-1)
else:
    print(cnt+min(startb,enda))

Submission status: Wrong Answer

Solution code:
N = int(input())

right_A = 0

left_B = 0

#others = 0

cnt = 0

flg = 0

for i in range(N) :
    S = input()
    
    cnt += S.count("AB")
    
    if S[-1] == "A" :
        right_A += 1
    
    if S[0] == "B" :
        left_B += 1
        
    if S[0] == "B" and S[-1] == "A" :
        flg = 1
                        

ans = min(right_A, left_B) + cnt - flg

print(ans)

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 ca >= n - 1 or cb >= n - 1:
    cnt -= 1
print(cnt + min(ca, cb))

Submission status: Wrong Answer

Solution code:
x = int(input())
a = 0
b = 0
c = 0
f = 1
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:
    a -= 1
if a < b:
    print(a+c)
else:
    print(b+c)

Submission status: Wrong Answer

Solution code:
N=int(input())
K=[]
ans=0
AA=0
BB=0
BA=0
for i in range(N):
    s=input().strip()
    ans+=s.count('AB')
    if s[0]=='B' and s[-1]=='A':
        BA+=1
    elif s[0]=='B':
        BB+=1
    elif s[-1]=='A':
        AA+=1
tmp=min(AA,BB)
tmp2=max(AA-tmp, BB-tmp)
tmp3=min(BA,tmp2)
if tmp3==tmp2 and tmp2!=0:
    tmp4=(BA-tmp3)
elif tmp3==tmp2 and tmp2==0:
    tmp4=(BA-tmp3)-1
else:
    tmp4=0
ans=ans+tmp+tmp3+tmp4
print(ans)

Submission status: Wrong Answer

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

a = 0
b = 0
a_b = 0

for s in S:
    if s[-1] == "A" and s[0] == "B":
        a_b += 1
    elif s[-1] == "A":
        a += 1
    elif s[0] == "B":
        b += 1

ans = a_b - 1
if a > 0:
    ans += 1
    a -= 1
if b > 0:
    ans += 1
    b -= 1

ans += min(a,b)

for line in S:
    for i in range(len(line)-1):
        if (line[i],line[i+1]) == ("A","B"):
            ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
a_count =0
b_count =0
ab_count =0
for i in range(N):
    test = str(input())
    if test[0] == "B":
        b_count +=1
    if test[-1] == "A":
        a_count += 1
    ab_count += test.count("AB")
print(ab_count+min(a_count,b_count))

Submission status: Wrong Answer

Solution code:
def countAB(S):
  ct=0
  flg = True
  pos=0
  while flg:
    idx = S.find('AB',pos)
    if idx!=-1:
      ct+=1
    else:
      flg = False
    pos = idx + 2
  return ct
 
N = int(input())
 
num_AB = 0
num_A = 0
num_B = 0
for n in range(N):
  S = input()
  num_AB += countAB(S)
  if S[len(S)-1]=='A':
    num_A += 1
  if S[0]=='B':
    num_B += 1
 
num_AB_cmb = min(num_A,num_B)
if num_A == N and num_B == N:
  num_AB_cmb = N-1
 
print("{0}".format(num_AB + num_AB_cmb))

Submission status: Wrong Answer

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

count = 0
Acount = 0
Bcount = 0

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

count += min(Bcount, Acount)
print(count)

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()
  if 'AB' in s:
    inAB += 1
  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:
import sys
input = sys.stdin.readline

import numpy as np

N = int(input())
S_list = [input().rstrip() for _ in range(N)]

S_ab_number = [i.count('AB') for i in S_list]
S_b_start_number = [1 if i[0] == 'B' else 0 for i in S_list]
S_a_end_number = [1 if i[-1] == 'A' else 0 for i in S_list]

print(sum(S_ab_number) + min(sum(S_b_start_number),sum(S_a_end_number)))

Submission status: Wrong Answer

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

ea, sb = 0, 0
ans = 0
sd = {(0, 1): 0, (1, 0): 0, (1, 1): 0}
for s in slist:
  for prevs, _s in zip(s, s[1:]):
    if prevs + _s == 'AB':
      ans += 1
  if s[0] == 'B' and s[-1] == 'A':
    sd[(1, 1)] += 1
  elif s[0] == 'B':
    sd[(0, 1)] += 1
  elif s[-1] == 'A':
    sd[(1, 0)] += 1

if sd[(0, 1)] > 0:
  sd[(0, 1)] -= 1
  ans += sd[(1, 1)]
else:
  ans += sd[(1, 1)] - 1
sd[(1, 1)] = 0
if sd[(1, 0)] > 0:
  ans += 1
  sd[(1, 0)] -= 1

print(ans + min(sd[(1, 0)], sd[(0, 1)]))

Submission status: Wrong Answer

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


def solve(N: int, s: "List[str]"):
    count = 0
    for string in s:
        count += string.count('AB')

    count_A = 0
    count_B = 0
    for string in s:
        if string[-1] == 'A':
            count_A += 1
        if string[0] == 'B':
            count_B += 1
    count += min(count_A, count_B)
    print(count)
    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())
s = []

result = 0
ABAB = 0
A = 0
B = 0
onon = 0

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

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

if ABAB >= 1:
    onon = onon + ABAB - 1

if A >= 1:
    onon += 1
if B >= 1:
    onon += 1



print(result + onon)

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 a == b:
    print(ans+a+ab//2)
else:
    print(ans+max(a,b)+max(0,(ab-abs(b-a))//2))

Submission status: Wrong Answer

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

bss = []
ass = []
css = []
for s in ss:
    if s[0] == 'B':
        bss.append(s)
    elif s[-1] == 'A':
        ass.append(s)
    else:
        css.append(s)

ans = ''
while len(bss) > 0 and len(ass) > 0:
    ans += ass[-1] + bss[-1]
    ass.pop()
    bss.pop()
while len(ass) > 0:
    ans += ass[-1]
    ass.pop()
while len(bss) > 0:
    ans += bss[-1]
    bss.pop()
while len(css) > 0:
    ans += css[-1]
    css.pop()

n = 0
p = 0
while p != -1:
    p = ans.find('AB', p)
    if p == -1:
        break
    n += 1
    p += 1

print(n)

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

count = count + min(end_A,eni_B) + both

print(count)

Submission status: Wrong Answer

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

print(cnt + min(bx, xa))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)


def read_int():
    return int(input())


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


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, S):
    ans = 0
    pre_b = 0
    post_a = 0
    for s in S:
        if s[0] == 'B':
            pre_b += 1
        if s[-1] == 'A':
            post_a += 1
        ans += s.count('AB')
    ans += min(min(pre_b, post_a), N-1)
    return ans


def main():
    N = read_int()
    S = [read_str() for _ in range(N)]
    print(slv(N, S))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())
flag = True
ans = 0
c_A = 0
c_B = 0
for i in range(N):
    S = input()
    if 'AB' in S:
        ans += 1
    if S[0] == 'B':
        c_B += 1
        if not(S[-1] == 'A'):
            flag = False
    if S[-1] == 'A':
        c_A += 1
        if not(S[0] == 'B'):
            flag = False
if c_B == 0 or c_A == 0:
    flag = False
print(ans + min(c_A,c_B) - flag)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
ss = [input() for _ in range(N)]
cnt = 0
ba = 0
b = 0
a = 0
o = 0
import re
for s in ss:
    cnt += len(re.findall('AB', s))
    if s[-1] == 'A' and s[0] == 'B':
        ba += 1
    elif s[-1] == 'A':
        a += 1
    elif s[0] == 'B':
        b += 1
    else:
        o += 1

if ba > 0:
    if b > 0 and a > 0:
        cnt += ba + 1 + min(a-1, b-1)
    else:
        cnt += ba
else:
    cnt += min(a, b)

print(cnt)

Submission status: Wrong Answer

Solution code:
n = int(input())

count = 0
frontb = False
lasta = False
temp = False
for _ in range(n):
  s = input()
  if "AB" in s:
    count += 1
  if s[-1] is "A":
    if frontb:
      count+=1
      frontb = False
    else:
      temp = True
  if s[0] is "B":
    if lasta:
      count+=1
      lasta = False
    else:
      frontb = True
  lasta = temp
    
print(count)

Submission status: Wrong Answer

Solution code:
def count(list):
    a,b=0,0
    for i in range(len(list)):
        if list[i][0]=='B':
            b+=1
        if list[i][-1]=='A':
            a+=1
    return min(a,b)
def check(string):
    c=0
    for i in range(len(string)-1):
        if string[i]=='A' and string[i+1]=='B':
            c+=1
    return c
n=int(input())
m,l=0,[]
for i in range(n):
    s=input()
    m+=check(s)
    
    l.append(s)
m+=count(l)

print(m)

Submission status: Wrong Answer

Solution code:
N=input()
LL=[]
def find(s):
    count=0
    for i in xrange(len(s)-1):
        if s[i]+s[i+1]=='AB':
            count+=1
    return count        

ans=0
start_B=0
end_A=0
same_time=0
for i in xrange(N):
    s=raw_input()
    ans+=find(s)
    if s[-1]=='A':
        end_A+=1
    if s[0]=='B':
        start_B+=1   
    if s[0]=='B' and s[-1]=='A':
        same_time+=1


#print(ans,end_A,start_B,same_time)
if end_A!=start_B:
    print(ans+min(end_A,start_B)-same_time+1+(same_time-1))
else:
    print(ans+min(end_A,start_B)-same_time+(same_time))

Submission status: Wrong Answer

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

end_A = 0
start_B = 0
AB_count = 0

for i in range(n):
    if 'AB' in s[i]:
        AB_count += 1
    if s[i][0] == 'B':
        start_B += 1
    if s[i][len(s[i])-1] == 'A':
        end_A += 1

print(AB_count + min(end_A, start_B))

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 20:47:47 2019

@author: Owner
"""

# -*- coding: utf-8 -*-
"""
Created on Sat Apr 13 09:53:12 2019

@author: Owner
"""
import numpy as np
import sys
import collections
import scipy.misc
import math
from operator import itemgetter
import itertools
import copy
import bisect

#素因数を並べる
def prime_decomposition(n):
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n /= i
      table.append(int(i))
    i += 1
  if n > 1:
    table.append(int(n))
  return table   
# 桁数を吐く
def digit(i):
    if i > 0:
        return digit(i//10) + [i%10]
    else:
        return []
    
def getNearestValueIndex(list, num):
    """
    概要: リストからある値に最も近い値のインデックスを取得する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return idx

def find_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default


"""
N, X = map(int, input().split())

x = list(map(int, input().split()))

P = [0]*N
Y = [0]*N
for n in range(N):
    P[n], Y[n] = map(int, input().split())

# 多次元配列の宣言（あとでintにすること。）（タプルにすること。）
dp = np.zeros((N+1, 4,4,4))
    
all(nstr.count(c) for c in '753')

# 複数配列を並び替え
ABT = zip(A, B, totAB)
result = 0
# itemgetterには何番目の配列をキーにしたいか渡します
sorted(ABT,key=itemgetter(2))
A, B, totAB = zip(*ABT)
A.sort(reverse=True)

# 2進数のbit判定
(x >> i) & 1

# dp最小化問題
dp = [np.inf]*N
for n in range(N):
    if n == 0:
        dp[n] = 0
    else:
        for k in range(1,K+1):
            if n-k >= 0:
                dp[n] = min(dp[n], dp[n-k] + abs(h[n]-h[n-k]))
            else:
                break
# 累積和
add = 1 # 問題によって決まる
res = 0
sums = [0]*(len(nums)+1)
for i in range(len(nums)):
    sums[i+1] = sums[i] + nums[i]
for i in range(0, len(nums), 2):
    left = i
    right = min(i+add, len(nums))
    tmp = sums[right] - sums[left]
    res = max(tmp, res)

#２分探索
li, ri = bisect.bisect_left(p_ac, l[i]-1), bisect.bisect_right(p_ac, r[i]-1)    

#ソート関数
org_list = [3, 1, 4, 5, 2]
new_list = sorted(org_list)
print(org_list)
print(new_list)
# [3, 1, 4, 5, 2]
# [1, 2, 3, 4, 5]

"""
N = int(input())

s = [""]*N

cnt  = 0
cnt_A= 0
cnt_B= 0
cnt_BA=0
for n in range(N):
    s[n] = input()
    cnt += s[n].count("AB")
    if s[n][0] == "B" and s[n][-1] == "A":
        cnt_BA+=1
    elif s[n][0]=="B":
        cnt_B +=1
    elif s[n][-1]=="A":
        cnt_A +=1
    else:
        pass
    
            

def main(): 
    #print(s, cnt)
    print(cnt + min(cnt_BA+cnt_B, cnt_BA+cnt_A))
    if cnt_A == 0 and cnt_B ==0:
        print(cnt + min(cnt_BA-1, cnt_BA-1))
    else:
        print(cnt + min(cnt_BA+cnt_B, cnt_BA+cnt_A))
                
                
                
            
            
                

    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
b = 0
a = 0
ans = 0
for i in range(n):
    s.append(input())
    ans += s[i].count('AB')
    if s[i].startswith('B'):
        b += 1
    if s[i].endswith('A'):
        a += 1

print(ans + min(a, b))

Submission status: Wrong Answer

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


ans = 0
A = B = BA = 0
for s in S:
    for i in range(len(s) - 1):
        if s[i] + s[i + 1] == 'AB':
            ans += 1

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


if A:
    ans += BA
    A -= 1
    if B:
        ans += 1
        B -= 1
    ans += min(A, B)
else:
    ans += max(0, BA - 1)
    if B:
        ans += 1

print(ans)

Submission status: Wrong Answer

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

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

print(ans + min(a, b))

Submission status: Wrong Answer

Solution code:
import re
n = int(input())
a = 0
b = 0
res = 0
for i in range(n):
    string = input()
    res += len( re.findall('AB', string))
    if string[0] == "B":
        b += 1
    if string[-1] == "A":
        a += 1

res += min(a, b)
print(res)

Submission status: Wrong Answer

Solution code:
# diverta 2019 Programming Contest
# https://atcoder.jp/contests/diverta2019
import sys

s2nn = lambda s: [int(c) for c in s.split(' ')]
ss2nn = lambda ss: [int(s) for s in list(ss)]
ss2nnn = lambda ss: [s2nn(s) for s in list(ss)]
i2s = lambda: sys.stdin.readline().rstrip()
i2n = lambda: int(i2s())
i2nn = lambda: s2nn(i2s())
ii2ss = lambda n: [sys.stdin.readline().rstrip() for _ in range(n)]
ii2nn = lambda n: ss2nn(ii2ss(n))
ii2nnn = lambda n: ss2nnn(ii2ss(n))

def main():
    N = i2n()
    S = ii2ss(N)
    c0b = 0
    c1a = 0
    c0b1a = 0
    c = 0
    for s in S:
        for i, t in enumerate(s[:-1]):
            if t == 'A':
                if s[i+1] == 'B':
                    c += 1
        if s[0] == 'B' and s[-1] == 'A':
            c0b1a += 1
        elif s[0] == 'B':
            c0b += 1
        elif s[-1] == 'A':
            c1a += 1
    c0b1a_min = min(c0b, c1a)
    c0b1a_max = max(c0b, c1a)
    c += c0b1a_min
    if c0b1a > 0:
        c += c0b1a - 1
        if c0b1a_max - c0b1a_min > 0:
            c += 1
    print(c)

main()

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:
    lr = 0
else:
    ans += (rs+ls)//2
ans += lr
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
a=[input() for i in range(n)]
count=0
ca=0
cb=0
cc=0
for i in a:
    count+=i.count('AB')
    if i[0]=='B':cb+=1
    if i[-1]=='A':ca+=1
    if i[0]=='B' and i[-1]=='A':cc+=1
ans=count+min(ca,cb)
if max(ca,cb)==cc:ans-=1
if len(a)==1:ans=a[0].count('AB')    
print(ans)

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')
count = count+min(aa,bb)
print(count)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)


def read_int():
    return int(input())


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


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, S):
    ans = 0
    pre_b = 0
    post_a = 0
    for s in S:
        if s[0] == 'B':
            pre_b += 1
        if s[-1] == 'A':
            post_a += 1
        ans += s.count('AB')
    return ans


def main():
    N = read_int()
    S = [read_str() for _ in range(N)]
    print(slv(N, S))


if __name__ == '__main__':
    main()

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" in str[0]:
        count_last += 1
    if "A" in str[-1]:
        count_first +=1

print(count+min(count_first, count_last))