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 sys
# import bisect
# import math
# import itertools
# import numpy as np

# import collections

"""Template"""


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

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

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

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

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

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

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

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

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

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


class Idea:
    def __init__(self):
        pass

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

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

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

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

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

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

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

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

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

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


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


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

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


main()

Submission status: Wrong Answer

Solution code:
n=int(input())
count_list=[]
b_a=0
b=0
a=0

for i in range(n):
    s=input()
    length=len(s)
    if s[0]=="B" and s[length-1]=="A":
        b_a=b_a+1
    if s[0]=="B":
        b=b+1
    if s[length-1]=="A":
        a=a+1
    count_list.append(s.count("AB"))
a=a-b_a
b=b-b_a
minimum=min(a+b_a, b+b_a)
if b==0 and a==0:
    print(sum(count_list)+minimum-1)
else:
    print(sum(count_list)+minimum)

Submission status: Wrong Answer

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

a = 0
b = 0
c = 0

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

c += min(min(a, b), n-1)
print(c)

Submission status: Wrong Answer

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

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

print(ok + min(b_start, a_end))

Submission status: Wrong Answer

Solution code:
# -*- 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_B += 1
        if s[-1] == 'A':
            count_AB += 1
    if s[-1] == 'A':
        count_A += 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())
S = [input() for _ in range(N)]
cnt1 = 0
cnt2 = 0
cnt3 = 0

for s in S:
  if "AB" in s:
    cnt1 += 1
  if s[0] == "B":
    cnt2 += 1
  if s[-1] == "A":
    cnt3 += 1

print(cnt1 + min(cnt2, cnt3))

Submission status: Wrong Answer

Solution code:
#Rs,Gs,Bs,Ns= input().split()
#R=int(Rs)
#G=int(Gs)
#B=int(Bs)
#N=int(Ns)
#ans=0
#sub_ans=0
#while(sub_ans>=N):

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

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

#print(f_a)
#print(b_b)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

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

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

ans = 0

x = y = z = 0

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

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

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

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

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

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

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

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
list1 = []
count1 = 0
check1 = 0
taila = 0
headb = 0

for i in range(N):
    list1.append(input())
    if list1[i][0] == "B":
         headb +=1
    if list1[i][len(list1[i])-1] == "A":
         taila +=1
    for j in list1[i]:
        if j == "A":
            check1 = 1
        if (check1 ==1 and j =="B"):
            count1 += 1
            check1 = 0
        if (j != "A" and j != "B"):
            check1 = 0

print(count1+min(headb,taila))

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
    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:
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')
        
print(ct+len(lis1)+min(len(lis2),len(lis3)))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
import re

N = int(input())
lst = []

for i in range(N):
    s = input()
    n = len(re.findall(r'AB', s))
    m = len(re.findall(r'A$', s))
    l = len(re.findall(r'^B', s))
    lst.append((n, m, l))


ans = sum([l[0] for l in lst]) + min(sum([l[1] for l in lst]), sum(l[2] for l in lst))
if sum(l[2] for l in lst) == sum([l[1] for l in lst]):
    ans -= 1
print(ans)

Submission status: Wrong Answer

Solution code:
l = raw_input().split()
N = int(l[0])
S = [0]*N
for i in range(N):
    l = raw_input().split()
    S[i] = l[0]

#print(N, S)

count = 0
for s in S:
    count += s.count('AB')
#print(count)

numA = 0
numB = 0
for s in S:
    if s[-1] == 'A':
        numA += 1
    if s[0] == 'B':
        numB += 1
print(count + min(numA, numB))

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
    
assert (last_a+head_b+head_last_both <= n)
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:
    if lower + connected < n:
        ans += 1
print(ans)

Submission status: Wrong Answer

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

base = len(list(filter((lambda x: x.find('AB') != -1), s)))

same_pattern = a_n = b_n = 0
for x in s:
    b = x[0]
    a = x[len(x)-1]
    if b == 'B':
        b_n += 1
    if a == 'A':
        a_n += 1
    if a == 'A' and b == 'B':
        same_pattern += 1

if same_pattern == a_n:
    print(base + a_n - 1)
else:
    print(base + min(a_n, b_n))

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for _ in range(n)]
start_b = len([i for i in s if i[0] == "B" and i[-1] != "A"])
end_a = len([i for i in s if i[-1] == "A" and i[0] != "B"])
both = len([i for i in s if i[0] == "B" and i[-1] == "A"])
include_ab = sum([i.count("AB") for i in s])

if both:
  end_a -= 1
  start_b -= 1
  include_ab += (both+1)

print(include_ab+min(start_b,end_a))

Submission status: Wrong Answer

Solution code:
N = int(input())
S = []
ab = []  # if include ab [num, ,] if b start [, 1], if a end [, ,1]
for i in range(N):
    S.append(input())

ab_num = 0
b_start = 0
a_end = 0
for i in range(N):
    s = S[i]
    for j in range(1, len(s)):
        if s[j] == 'B' and s[j-1] == 'A':
            ab_num += 1
    if s[0] == 'B':
        b_start += 1
    if s[len(s)-1] == 'A':
        a_end += 1

print(ab_num + min(a_end, b_start))

Submission status: Wrong Answer

Solution code:
import re

N = int(input())

cnt = 0
tail_A = 0
head_B = 0

for i in range(N):
    s = input()
    if s[0] == 'B':
        head_B += 1
    if s[-1] == 'A':
        tail_A += 1
    matchedList = re.findall(r"AB", s)
    cnt += len(matchedList)

cnt += min(tail_A, head_B)

print(cnt)

Submission status: Wrong Answer

Solution code:
N = int(input())
line = list()
counter = 0
a_parts = 0
b_parts = 0
for i in range(N):
    temp = input()
    counter += temp.count('AB')
    temp.replace('AB', '')
    if temp[-1] == 'A':
        a_parts += 1
    if temp[0] == 'B':
        b_parts += 1
if a_parts < b_parts:
    counter += a_parts
else:
    counter += b_parts
print(counter)

Submission status: Wrong Answer

Solution code:
from sys import stdin
# import numpy as np
# import math
# import fractions
# import sys
# sys.setrecursionlimit(100000)
# N = int(stdin.readline().rstrip().split()[0])
# A = [int(x) for x in stdin.readline().rstrip().split()]
# N, X = [int(x) for x in stdin.readline().rstrip().split()]
# S = stdin.readline().rstrip().split()[0]

N = int(stdin.readline().rstrip().split()[0])

_A = 0
AB = 0
B_ = 0
B_A = 0
for _ in range(N):
  s = stdin.readline().rstrip().split()[0]
  AB += s.count("AB")
  a=0
  b=0
  if s[0] == "B":
    b = 1
  if s[-1] == "A":
    a = 1
  if a == 1 and b == 1:
    B_A += 1
  _A += a
  B_ += b

if _A == B_ == B_A:
  print(max(0, AB+B_A-1))
else:
  _AB_ = min(_A, B_)
  print(AB+_AB_)

Submission status: Wrong Answer

Solution code:
N = int(input())

ans = 0
A_flag = 0
B_flag = 0
for i in range(N):
    S = input()
    ans += S.count('AB')

    if S[0] == 'B':
        if A_flag:
            ans += 1
            A_flag -= 1
        else:
            B_flag += 1

    if S[-1] == 'A':
        if B_flag:
            ans += 1
            B_flag -=1
        else:
            A_flag += 1

if A_flag*B_flag != 0:
    ans += min(A_flag,B_flag)
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
f=0
b=0
c=0
d=0
a=0
k=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+=1
    if s[0]=="B" and s[len(s)-1]!="A":
        a+=1
    if s[len(s)-1]=="A" and s[0]!="B":
        k+=1
e=0
if min(a,k)<d:
    e=1
print(c+min(f,b)-e)

Submission status: Wrong Answer

Solution code:
N = int(input())

s = []
Binfront = 0
Ainend = 0
ABs = 0
for i in range(N):
    inputstring = input()
    s.append(inputstring)
    ABs += inputstring.count("AB")
    if inputstring[0] == "B":
        Binfront += 1
    if inputstring[len(inputstring)-1] == "A":
        Ainend += 1

ABs += min(Ainend,Binfront)

print(ABs)

Submission status: Wrong Answer

Solution code:
N = int(input())

cnt = 0
list = [0,0,0]

for i in range(N):
    s = input()
    cnt += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        list[0] += 1
    elif s[-1] == 'A':
        list[1] += 1
    elif s[0] == 'B':
        list[2] += 1

if list[0] >= 2:
    cnt += 2*list[0]//2
    list[0] -= 2*(list[0]//2)

if list[1] == list[2]:
    cnt += list[1]
elif list[1] > list[2]:
    cnt += list[2] + min(list[0],list[1]-list[2])
elif list[1] < list[2]:
    cnt += list[1] + min(list[0],list[2]-list[1])

print(cnt)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

if a>0 and b>0 and ab>0:
    print(count + ab + min(a,b))
elif ab == 0:
    print(count + min(a,b))
else:
    print(count + ab)

Submission status: Wrong Answer

Solution code:
N = int(input())
AB_number = 0
a_cnt = 0
b_cnt = 0
for _ in range(N):
    s_i = input()
    AB_number += s_i.count("AB")
    if s_i[0] == "B":
        b_cnt += 1
    if s_i[-1] == "A":
        a_cnt += 1

print(AB_number+min(a_cnt,b_cnt))

Submission status: Wrong Answer

Solution code:
import math
n = int(input())

s=[]
res = 0
tmp = 0
eA=0
sB=0
eAsB=0
for i in range(n):
#	s.append(list(input()))
	s.append(input())
	tmp = s[i].count("AB")
	if tmp != 0:
		res += tmp
	if s[i][0]=="B" and s[i][-1]=="A":
		eAsB += 1
	elif s[i][-1]=="A":
		eA += 1
	elif s[i][0]=="B":
		sB += 1
		
res += min(eA, sB)
if eA < sB:
	res += min(sB-eA, eAsB)
	if (sB-eA) < eAsB:
		res += math.floor(eAsB-(sB-eA)/2)
else:
	res += min(eA-sB, eAsB)
	if (eA-sB) < eAsB:
		res += math.floor(eAsB-(eA-sB)/2)

print(res)
#print(eA)
#print(sB)
#print(eAsB)

Submission status: Wrong Answer

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

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

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

Submission status: Wrong Answer

Solution code:
n=int(input())
s=[]
ctr=0
ctr_a=0
ctr_b=0
ctr_ab=0
for i in range(n):
    s.append(str(input()))
    if "AB" in s[i]:
        ctr+=s[i].count("AB")
    if s[i][-1]=="A":
        ctr_a+=1
    if s[i][0]=="B":
        ctr_b+=1
    if s[i][-1]=="A" and s[i][0]=="B":
        ctr_ab+=1
if ctr_a==ctr_b==ctr_ab:
    print(ctr+ctr_ab-1)
else:
    print(ctr+min(ctr_a,ctr_b))

Submission status: Wrong Answer

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

N = int(input())
s_li = []
for _ in range(N):
    s_li.append(input().strip())

last_is_A = 0
first_is_B = 0
both_conditions_are_true = 0
AB_counter = 0
for i in s_li:
    if i[-1] == 'A': last_is_A += 1
    if i[0] == 'B': first_is_B += 1
    if i[-1] == 'A' and i[0] == 'B': both_conditions_are_true += 1
    AB_counter += i.count('AB')

if both_conditions_are_true == last_is_A == first_is_B:
    print(AB_counter + min(last_is_A, first_is_B, N-1, both_conditions_are_true-1))
else:
    print(AB_counter + min(last_is_A, first_is_B, N-1))

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 and l != 0 and m != 0:
    ans += 1
print(ans)

Submission status: Wrong Answer

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

start = 0
end = 0
flg = False
c = 0
for x in s:
    if 'AB' in x:
        c += 1
    if x.startswith('B'):
        start += 1
        if x.endswith('A'):
            flg = True
    if x.endswith('A'):
        end += 1

if start == end:
    c += start
    if flg:
        c  -= 1
elif start > end:
    c += end
else:
    c += start
print(c)

Submission status: Wrong Answer

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


print(ans + min(min(A,B), N-1))

Submission status: Wrong Answer

Solution code:
N = int(input())
s = [input() for i in range(N)]
abc = sum([e.count("AB") for e in s]) # 各文字列のAB出現回数
bstart, aend = 0, 0
B_A = 0
for e in s:
    if e[0] == "B":
        bstart += 1
    if e[-1] == "A":
        aend += 1
    if e[0] == "B" and e[-1] == "A":
        B_A += 1
makedB_A = min(bstart-B_A, aend-B_A)
ans = 0

if bstart == aend:
    if makedB_A == 0:
        ans = abc + bstart
    else:
        ans = abc + bstart - 1
else:
    ans = abc + min(bstart, aend)

    
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s_array = [input() for x in range(n)]
last_a = 0
for s in s_array:
    if s[-1] == "A":
        last_a += 1

start_b = 0
flag = False
for s in s_array:
    if s[0] == "B":
        start_b += 1
    else:
        flag = True
res = 0
for s in s_array:
    res += s.count("AB")

if start_b > last_a or flag:
    tmp = 0
else:
    tmp = 1
print(res + min(last_a, start_b) - tmp)

Submission status: Wrong Answer

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

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

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

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

    
print(res)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

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

ss = [input() for i in range(N)]

ss_ab_count = sum([s.count('AB') for s in ss])

end_a_count = sum([1 for s in ss if s[-1] == 'A'])
start_b_count = sum([1 for s in ss if s[0] == 'B'])

if start_b_count < end_a_count:
    count = ss_ab_count + start_b_count
else:
    count = ss_ab_count + end_a_count

print(count)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()

n = ni()
_anum = 0
b_num = 0
banum = 0
ct = 0
for i in range(n):
    st = input()
    ct += st.count('AB')
    if st.startswith('B'):
        if st.endswith('A'):
            banum += 1
        else:
            b_num += 1
    else:
        if st.endswith("A"):
            _anum += 1
if banum > 1:
    print(ct + min(_anum, b_num) + (banum - 1) + abs(_anum - b_num))
else:
    print(ct + min(_anum, b_num))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/python3

n = int(input())

cnt=0
cnt_a=0
cnt_b=0

for i in range(n):
    s=input()
    cnt += s.count("AB")
    if s[-1]=='A':
        cnt_a+=1;
    if s[0]=='B':
        cnt_b+=1;

cnt += min(cnt_a,cnt_b)
if n == min(cnt_a,cnt_b):
    cnt-=1

print(cnt)

Submission status: Wrong Answer

Solution code:
N = int(input())
cnt = 0
SB = 0
EA = 0
SBEA = 0

for i in range(N):
    s = input()
    cnt += s.count("AB")
    if s.startswith("B"):
        if s.endswith("A"):
            SBEA += 1
        else:
            SB += 1
    elif s.endswith("A"):
        EA += 1

if SBEA > 0:
    cnt += SBEA
    if SB > 0:
        cnt += 1
        SB -= 1
    if EA > 0:
        cnt +- 1
        EA -= 1

cnt += min(SB,EA)

print(cnt)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n=int(input())
s=[]
count=0
bstart=0
aend=0
ab=0

for i in range(n):
  s.append(input())
for i in s:
  if i[0]=="B":
    bstart+=1
  if i[len(i)-1]=="A":
    aend+=1
  if i[0]=="B" and i[len(i)-1]=="A":
    ab+=1
  prec=""
  for j in i:
    if prec=="A" and j=="B":
      count+=1
    else:
      prec=j

if ab!=aend or ab!=bstart:
  print(count+min(bstart,aend))
else:
  print(count+min(bstart,aend)-1)

Submission status: Wrong Answer

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

if N == 1:
    print(S[0].count("AB"))
    quit()

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

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

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
S = []
count = 0
countA = 0
countB = 0
for i in range(N):
	S_in = str(input())
	for j in range(len(S_in)-1):
		if S_in[j:j+2] == 'AB':
			count += 1
	if S_in[0] == 'B':
		countB += 1
	if S_in[-1] == 'A':
		countA += 1
	S.append(S_in)
if (countA == N) & (countA == countB):
	print(count+countA-1)
else:
	print(count+min(countA,countB))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
cnt = 0
na = 0
nb = 0
nc = 0
for i in range(N):
    s = input()
    cnt += s.count('AB')
    if s[-1] == 'A':
        na += 1
    if s[0] == 'B':
        nb += 1
    if (s[-1] == 'A') and (s[0] == 'B'):
        nc +=  1
if(na == nc):
    add = min(na,nb)-1
else:
    add = min(na,nb)
print(cnt+add)

Submission status: Wrong Answer

Solution code:
n=int(input())
cnt_a=0
cnt_b=0
cnt_ab=0
cnt_bxa=0
for i in range(n):
  s=input()
  if s[0]=='B' and s[-1]!='A':
    cnt_b+=1
  if s[-1]=='A' and s[0]!='B':
    cnt_a+=1
  if s[0]=='B' and s[-1]=='A':
    cnt_bxa+=1
  for i in range(len(s)-1):
    if s[i:i+2]=='AB':
      cnt_ab+=1
ans=0
ans+=cnt_ab
if cnt_a==0:
  ans+=cnt_bxa-1
  if cnt_b>0:
    ans+=1
else:
  ans+=cnt_bxa
  ans+=min(cnt_a,cnt_b)
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
bb = 0
af = 0
ab = 0
p = 1
for i in range(n):
  s = input()
  l = len(s)
  if s[0] == "B":
    bb += 1
  if s[l - 1] == "A":
    af += 1
  if s[0] == "B" and s[l - 1] != "A":
    p = 0
  if s[0] != "B" and s[l - 1] == "A":
    p = 0
  for j in range(l - 1):
    if s[j] == "A":
      if s[j + 1] == "B":
        ab += 1
if af == bb:
  if af == n:
    ans = ab + n - 1
  else:
    ans = ab + af - p
else:
  ans = ab + min(af, bb)
print(ans)

Submission status: Wrong Answer

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

bxa = min(bx, xa)
if bxa == n:
  bxa -= 1
print(cnt + bxa)

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

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