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 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) == 0:
            break
        if len(s) > 1:
            if s[0:2] == 'AB':
                s = s[2:]
                num_ab += 1
            else:
                break
        else:
            break
    while True:
        if len(s) == 0:
            break
        if len(s) > 1:
            if s[-2:] == 'AB':
                s = s[:-2]
                num_ab += 1
            else:
                break
        else:
            break
#     print(s)
    if len(s) > 0:
        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)
        

    while True:
        i = s.find('AB')
        if i >= 0:
            num_ab += 1
            s = s[i + 2:]
        else:
            break
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])
        
print(num_ab)

Submission status: Wrong Answer

Solution code:
import sys

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

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

pair = min(eA, sB)
if sB > 0 or eA > 0:
  ans = inAB + both + pair
else:
  ans = inAB + both - 1
print(max(ans, 0))

Submission status: Wrong Answer

Solution code:
N=int(input())
S=[input() for _ in range(N)]
count=0
cA=0
cB=0
for s in S:
  if s[-1]=='A':
    s=s[:-1]
    cA+=1
  if s[0]=='B':
    s=s[1:]
    cB+=1
print("0".join(S).count('AB')+min(cA,cB))

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

if both >0:
    cnt += both -1
    both = 1

con_cnt_min,con_cnt_max = min(topb,taila),max(topb,taila)
con_cnt = min(con_cnt_min+both,con_cnt_max)
print(cnt + con_cnt)

Submission status: Wrong Answer

Solution code:
N = int(input())
A=0
B=0
BA=0
ans=0
for i in range(N):
  s = input()
  last = len(s)-1
  ans += s.count('AB')
  if s[0]=='B' and s[last]=='A':
    A+=1
    B+=1
    BA+=1
  elif s[0]=='B':
    B+=1
  elif s[last]=='A':
    A+=1
ans += min(A,B)
if A==B and B==BA:
  ans-=1
print(max(0,ans))

Submission status: Wrong Answer

Solution code:
from sys import stdin
import math
import fractions
from collections import deque

INF = 10 ** 10

N = int(stdin.readline().rstrip())
s = [stdin.readline().rstrip() for _ in range(N)]

endA_num = 0
startB_num = 0

cnt = 0
for si in s:
    if si[-1] == "A":
        endA_num += 1
    if si[0] == "B":
        startB_num += 1

    for i in range(len(si)-1):
        if si[i] == "A" and si[i+1] == "B":
            cnt+=1

alpha = 0
if endA_num > 0 and startB_num > 0:
    alpha = min(endA_num, startB_num)

print(cnt+alpha)

Submission status: Wrong Answer

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

if n == 1:
  print(cnt)
  exit()
if a >= 1:
  cnt += 1
  a -= 1
if b >= 1:
  cnt += 1
  b -= 1
print(cnt + f - 1 + min(a, b))

Submission status: Wrong Answer

Solution code:
import re

N = int(input())

startB = 0
stopA = 0
BtoA = 0
AB = 0

for i in range(N):
    s = input()
    if s.startswith("B") and s.endswith("A"):
        BtoA += 1
    elif s.startswith("B"):
        startB += 1
    elif s.endswith("A"):
        stopA += 1
    
    AB += len(re.findall("AB", s))

print(AB + min(startB, stopA) + min (abs(startB - stopA), BtoA))

Submission status: Wrong Answer

Solution code:

# coding: utf-8

# In[5]:

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


# In[12]:

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:
    ab_cnt += 1
if max(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[ ]:

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
S = [input() for i in range(int(input()))]
ans = 0
first_B = 0
end_A = 0
print(S)
for i in S:
    ans += i.count("AB")
    if(i[0] == "B"):
        first_B += 1
    if(i[-1] == "A"):
        end_A += 1
print(ans+min(first_B,end_A))

Submission status: Wrong Answer

Solution code:
N = int(input())
num_tail_A = 0
num_head_B = 0
count = 0
for i in range(N):
  s = input()
  count += s.count('AB')
  if(s[len(s)-1]  in 'A'):
    num_tail_A += 1
  if(s[0] in 'B'):
    num_head_B += 1
if(num_tail_A != num_head_B):
  result = count + min(num_tail_A, num_head_B)
else:
  result = result = count +num_tail_A - 1
print(result)

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)
print(AB+min(start_B,end_A)+min(amari,sB_eA))

Submission status: Wrong Answer

Solution code:
def main():
    n = int(input())
    s = [input() for i in range(n)]

    AB = 0
    B_ = 0
    _A = 0
    B_A = 0
    for ss in s:
        for i in range(len(ss)-1):
            if ss[i:i+2] == 'AB':
                AB += 1
        if ss[0] == 'B':
            if ss[-1] == 'A':
                B_A += 1
            else:
                B_ += 1
        elif ss[-1] == 'A':
            _A += 1
    print(AB + max((B_A - 1), 0) + max(min(B_ + int(B_A > 0), _A), min(B_, _A + int(B_A > 0))))
    # print(AB, B_, _A, B_A)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

c = 0
a = 0
b = 0
ab = 0

for i in range(0, n):
    for j in range(1, len(s[i])):
        if s[i][j-1:j+1] == "AB":
            c += 1
    if s[i][0] == "A" and s[i][-1] == "B":
        ab += 1
    else: 
        if s[i][0] == "B":
            b += 1
        if s[i][-1] == "A":
            a += 1

s = c
s += min(a, b)
a -= min(a, b)
b -= min(a, b)

if(ab > 0):
    s += ab - 1
    if(a > 0):
        s += 1
    if(b > 0):
        s += 1
        
print(s)

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()
elif a==b:
    print(a+b+c+max(d-1,0))
    exit()
ans=min(a,b)+c
dif=abs(a-b)
ans+=min(dif,d)
d-=min(dif,d)
print(ans+d)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for i in range(n)]
count = 0
countA=0
countB=0
countAB = 0
for i in s:
    count += i.count("AB")
    if (i[-1:] == "A"):
        countA +=  1
    if (i[0] == "B"):
        countB += 1
    if (i[-1:] == "A" and i[0] == "B"):
        countAB += 1
countC = (countA,countB)
ans = count+min(countC)
if(abs(countA-countB)>countAB):
    ans-=countAB
print(ans)

Submission status: Wrong Answer

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

N = int(input())

count_AB = 0
count_last_A = 0
count_first_B = 0
count_both = 0
for i in range(N):
    s = input().rstrip()
    
    count_AB += len(s.split('AB')) - 1
    
    if s[0] == 'B' and s[-1] == 'A':
        count_both += 1
    elif s[0] == 'B':
        count_first_B += 1
    elif s[-1] == 'A' :
        count_last_A += 1

temp = 0
if count_both > 0:
    temp += count_both - 1
    count_both = 1

max_AB = max(count_last_A, count_first_B)
min_AB = min(count_last_A, count_first_B)
temp += min_AB
max_AB -= min_AB
min_AB = 0

if max_AB - min_AB > count_both:
    temp += count_both
else:
    temp += max_AB + (count_both - max_AB) // 2

print(count_AB + temp)

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

c=0
for i in range(flag_c):
    if min(a_end,b_start)>0:
        a_end-=1
        b_start-=1
        c+=1

ans+=2*c
a_end-=c
b_start-=c
ans+=min(a_end,b_start)
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())

count_ab = 0
count_b = 0
count_a = 0
for i in range(n):
    a = input()
    if 'AB' in a:
        count_ab += 1

    if a[0]=='B':
        count_b += 1
    if a[len(a)-1] == 'A':
        count_a += 1

print(count_ab + min(count_a, count_b))

Submission status: Wrong Answer

Solution code:
N = int(input())
s = []
a = []
b = []
num_of_ab = 0
for i in range(N):
    temp = input()
    b.append(temp[0])
    s.append(temp)
    a.append(temp[-1])

for i in range(N):
    num_of_ab += s[i].count("AB")

ans = num_of_ab + min(a.count("A"), b.count("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 x == 0 and y == 0:
            ans += z-1
        else:
            ans += z

print(ans)

Submission status: Wrong Answer

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

S_in = [s for s in S if 'AB' in s]

num1 = 0
num2 = 0
num3 = 0
num4 = 0

for s in S:
  num1 += s.count('AB')
  if s[0] == 'B' and s[len(s)-1] == 'A' : num4 += 1
  else :
    if s[0] == 'B' : num2 += 1
    if s[len(s)-1] == 'A' : num3 += 1
num = num1+min(num2+num4,num3+num4)

print(num)

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 (a != 0 and ab != 0) or (b != 0 and ab != 0) or (a != 0 and b != 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 = [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 += d

res += min(t, l)

if d > 0 and max(t, l) - min(t, l) > 0:
    res += 1
    
    
print(res)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [list(input()) for i in range(n)]
a,b,c = 0,0,0
t = 0
for i in range(n):
        for j in range(len(s[i])-1):
                if s[i][j] == "A" and s[i][j+1] == "B":
                        c += 1
        if s[i][0] == "B":
                b += 1
        if s[i][-1] == "A":
                a += 1
        if s[i][0] == "B" and s[i][-1] == "A":
                t += 1

if a > b:
        d = b
else:
        d = a

if t == d:
        d = d - 1

print(d + c)

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 = []
	xA = 0
	Bx = 0
	BA = 0
	for _ in range(N):
		tmp = input()
		tmp = tmp[:-1]
		S.append(tmp)
		if tmp[0] == "B" and tmp[-1] == "A":
			BA += 1
			continue
		if tmp[-1] == "A":
			xA += 1
		if tmp[0] == "B":
			Bx += 1

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

	#print("{} {} {}".format(xA, Bx, BA))
	#print(ans)
	pls = 0
	if xA > 0 and Bx > 0:
		xA -= 1
		Bx -= 1

		pls = pls + 1 + BA
		BA == 0
	
	#print(pls)
	pls2 = 0
	if xA > 0 and Bx == 0 and BA > 0:
		xA -= 1
		pls2 = BA
		BA == 0
	
	#print(pls2)
	pls3 = 0
	if Bx > 0 and xA == 0 and BA > 0:
		Bx -= 1
		pls3 = BA
		BA == 0
	
	#print(pls3)
	print(ans + pls + pls2 + pls3 + min(xA, Bx, N - 1))

	
if __name__ == "__main__":
	main()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:

# coding: utf-8

# In[5]:

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


# In[12]:

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:
    ab_cnt += 1
if max(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[ ]:

Submission status: Wrong Answer

Solution code:
n = int(input())

ans = 0
A = 0
B = 0
AB = 0
for _ in range(n):
    s = input()
    ans += s.count('AB')
    
    if s[-1] == 'A' and s[0] != 'B':
        A += 1 
    if s[0] == 'B' and s[-1] != 'A':
        B += 1
    if s[-1] == 'A' and s[0] == 'B':
        AB += 1

        
ans += min(A, B)
rest_A_B = max(A, B) - min(A, B)
ans += min(rest_A_B, AB)
rest_AB = max(rest_A_B, AB) - min(rest_A_B, AB)
ans += rest_AB // 2

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())

if N == 1:
    S = input()
    print(S.count("AB"))
else:
    n_ab = 0
    n_b = 0
    n_a = 0
    for i in range(N):
        S = input()
        # 前後情報とABの数だけ調べておく
        n_ab += S.count("AB")
        if S[-1] == "A":
            n_a += 1
        if S[0] == "B":
            n_b += 1
    print(n_ab+min(n_b,n_a))

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for u in range(n)]
a = sum([u.count("AB") for u in s])
b = len([1 for u in s if u.endswith("A")])
c = len([1 for u in s if u.startswith("B")])
d = len([1 for u in s if u.endswith("A") and u.startswith("B")])
if (b==c and c==d):
  print(a+b-1)
else:
  print(a+min(b,c))

Submission status: Wrong Answer

Solution code:
n = int(input())
listA = list(input() for i in range(n))
a = 0
b = 0
c = 0
d = 0
for j in range(n):
    a = a + listA[j].count("AB")
for k in range(n):
    if listA[k][0]=="B":
        b = b+1
    if listA[k][-1]=="A":
        c = c+1
    if listA[k][0]=="B" and listA[k][-1]=="A":
        d = d+1
if b==d and c==d:
  b=b-1
print(a+min(b,c))

Submission status: Wrong Answer

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

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
f_b = 0
a_b = 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
    elif tmp2 == "B" :
      is_a = 0
      is_b = 1
      if char[0] == tmp2 :
        front += 1
        f_b = 1
  if is_a == 1 :
    back += 1
    if f_b == 1 :
      a_b += 1
  is_a = 0
  is_b = 0
  f_b = 0
if front >= back :
  is_ab += back
elif back > front :
  is_ab += front
if a_b > 1 :
  is_ab -= 1
print(is_ab)

Submission status: Wrong Answer

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

ab_count = 0
last_a_and_first_b_count = 0
last_a_count = 0
first_b_count = 0
for s in sn:
    ab_count += s.count('AB')
    if s[-1] == 'A' and s[0] == 'B':
        last_a_and_first_b_count += 1
    else:
        if s[-1] == 'A':
            last_a_count += 1
        if s[0] == 'B':
            first_b_count += 1

if last_a_and_first_b_count == 0:
    v = min(last_a_count, first_b_count)
else:
    if last_a_count == 0 and first_b_count == 0:
        v = 0
    elif last_a_count == 0 and first_b_count > 0:
        v = first_b_count + last_a_and_first_b_count - 1
    elif last_a_count > 0 and first_b_count == 0:
        v = last_a_count + last_a_and_first_b_count - 1
    else:
        v = min(last_a_count, first_b_count) + last_a_and_first_b_count

print(ab_count + v)

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

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

cnt = 0
both_ab = 0
last_a = 0
initial_b = 0
for i in range(N):
    cnt += s[i].count('AB')

    if s[i][-1] == 'A' and s[i][0] == 'B':
        both_ab += 1
    elif s[i][-1] == 'A':
        last_a += 1
    elif s[i][0] == 'B':
        initial_b += 1

min_a_b = min(initial_b, last_a)
cnt += min_a_b
diff_a_b = 0
if last_a - min_a_b == 0:
    diff_a_b = initial_b - min_a_b
else:
    diff_a_b = last_a - min_a_b
second = min(both_ab, diff_a_b)
cnt += second
if both_ab - second > 0:
    final = both_ab - second
    cnt += final - 1
    if both_ab > 1:
        cnt += 1


print(cnt)

Submission status: Wrong Answer

Solution code:
from sys import stdin
import math
import itertools


def makeIntMatrix(lines):
    intMatrix = []
    for a in makeStringMatrix(lines):
        intMatrix.append([int(b) for b in a])
    return intMatrix
 
 
def makeStringMatrix(lines):
    stringMatrix = [line.rstrip() for line in lines]
    return stringMatrix
 
 
def makeInt(line):
    return int(line.rstrip())
 
 
def makeMultiInteger(line):
    return [int(x) for x in line.rstrip().split()]


def solve(input_string):
    N = makeInt(input_string[0])
    S = makeStringMatrix(input_string[1:])
    #print(S)
    C_S_has_ab = []
    for s_index, s in enumerate(S):
        C_S_has_ab.append(0)
        for i in range(len(s)-1):
            if s[i] + s[i+1] == 'AB':
                C_S_has_ab[s_index] += 1
    #print(C_S_has_ab)
    _sum = 0
    _sum += sum(C_S_has_ab) 
    c_head_has_b = 0
    c_tail_has_a = 0
    c_head_tail_has_a_and_b = 0
    for s in S:
        if s[0] == 'B':
            c_head_has_b += 1
        if s[-1] == 'A':
            c_tail_has_a += 1
        if s[0] == 'B' and s[-1] == 'A':
            c_head_tail_has_a_and_b += 1
    #print(c_tail_has_a, c_tail_has_a, c_head_tail_has_a_and_b)
    #count_combi_a_b = c_tail_has_a * c_tail_has_a - c_head_tail_has_a_and_b
    count_combi_a_b = min(c_tail_has_a, c_tail_has_a) - c_head_tail_has_a_and_b + 1
    #- c_head_tail_has_a_and_b
    _sum += count_combi_a_b
    #print(_sum)
    return _sum


def main():
    input_lines = stdin.readlines()
    answer = solve(input_lines)
    print(answer)


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"])
if headcount==outcount:
    print(sum(count) + min(headcount, outcount)-1)
else:
    print(sum(count)+min(headcount,outcount))

Submission status: Wrong Answer

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

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

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

if len(bass) > 0:
    if len(ass) == 0:
        ass.append(bass.pop())
    if len(bss) == 0:
        bss.append(bass.pop())

while len(bss) > 0 and len(ass) > 0:
    ans += ass[-1] + bss[-1]
    ass.pop()
    bss.pop()
    if len(ass) == 0 and len(bass) > 0:
        ass.append(bass.pop())
    if len(bss) == 0 and len(bass) > 0:
        bss.append(bass.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()
print(ans)
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:
import sys

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

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

pair = min(eA, sB)
if sB > 0 or eA > 0:
  ans = inAB + both + pair
else:
  ans = inAB + both - 1
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = []
for _ in range(N):
    S.append(input())
ans = 0
a = list(filter(lambda x: "AB" not in x, S))
ans += len(S)-len(a)
b = 0
a = 0
for s in S:
    if s[0]=="B":
        b += 1
    if s[-1]=="A":
        a += 1
ans += min(a, b)
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())

cnt = 0
a_flag = 0
b_flag = 0
ab_flag = 0

s = [0]*n
for i in range(n):
    s[i] = input()

    for j in range(len(s[i])-1):
        if s[i][j:j+2] == 'AB':
            cnt += 1

    if s[i][0] == 'B':
        b_flag += 1
    if s[i][-1] == 'A':
        a_flag += 1
    if s[i][0] == 'B' and s[i][-1] == 'A':
        ab_flag += 1

ans = cnt + min(a_flag, b_flag)
print(ans if ab_flag%2==0 else ans - 1)

Submission status: Wrong Answer

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

import os
import sys
from io import BytesIO, IOBase

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


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

    a = b = mi = 0

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

    print(mi + min(a, b) - 1)


# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

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

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

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

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


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


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

# endregion

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n,*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()
elif a==b:
    print(a+b+max(d-1,0))
    exit()
ans=min(a,b)+c
dif=abs(a-b)
ans+=min(dif,d)
d-=min(dif,d)
print(ans+d)

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)
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
    if c % (a-b) > 0:
        cnt += c % (a-b)
elif b > a:
    cnt += a
    cnt += c
    if c % (b-a) > 0:
        cnt += c % (b-a)

print(cnt)

Submission status: Wrong Answer

Solution code:
a=input()
a=int(a)
ll=[]
count=0
pcount=0
ll=[]
for i in range(a):
    switch=0
    ap=0
    bp=0
    b=input()
    ofset=0
    for i in b:
        if i=="B" and ofset==0:
            bp+=1
        elif i=="A":
            switch+=1
            ofset+=1
            continue
        elif i=="B" and switch==1:
            count+=1
            switch=0
        ofset+=1
    if switch==1:
        ap=1
    if ap==1 and bp==1:
        ll.append("AB")
    elif ap==1:
        ll.append("A")
    elif bp==1:
        ll.append("B")
pp=a-1
kkk=0
while 1:
    ac=0
    bc=0
    abc=0
    if ll.count("A")>0:
        ac=1
    if ll.count("B")>0:
        bc=1
    if ll.count("AB")>0:
        abc=1
    if ll.count("AB")>1:
        abc=2
    if ac+bc+abc<2:
        break
    if pp==0:
        break
    if "A" in ll and "B" in ll and pp>0:
        count+=1
        pp-=1
        ll.remove("A")
        ll.remove("B")
    if "A" in ll and "AB" in ll and pp>0:
        count+=1
        pp-=1
        ll.remove("A")
        ll.remove("AB")
        ll.append("A")
    if "AB" in ll and "B" in ll and pp>0:
        count+=1
        pp-=1
        ll.remove("AB")
        ll.remove("B")
        ll.append("B")
    if ll.count("AB")==2 and pp>0:
        count+=1
        pp-=1
        ll.remove("AB")
        ll.remove("AB")
        ll.append("?")
    if "A" in ll and "?" in ll and pp>0:
        count+=1
        pp-=1
        ll.remove("A")
        ll.remove("?")
    if "B" in ll and "?" in ll and pp>0:
        count+=1
        pp-=1
        ll.remove("B")
        ll.remove("?")
    if "AB" in ll and "?" in ll and pp>0:
        count+=1
        pp-=1
        ll.remove("AB")
    if ll.count("?")>1:
        count+=1
        pp-=1
        ll.remove("?")
    
print(count)

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]
S_both_number = [1 if i[-1] == 'A' and i[0] == 'B' else 0 for i in S_list]

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