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

mod = 10**9+7

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






cnt += min(min(A_cnt,B_cnt),N-1)

print(cnt)

Submission status: Wrong Answer

Solution code:
N = int(input())

moji_list = []
A_count = 0
B_count = 0
AB_count = 0

if N == 1:
    moji = input()
    print(moji.count('AB'))

else:
    for i in range(N):
        moji = input()
        if moji[0] == 'B':
            B_count += 1
        if moji[-1] == 'A':
            A_count += 1
        
        AB_count += moji.count('AB')

    if A_count >= B_count:
        print(AB_count+B_count)
    else:
        print(AB_count+A_count)

Submission status: Wrong Answer

Solution code:
n = int(input())

ans = 0
S = []
right_A = 0
left_B = 0
for _ in range(n):
    s = input()
    S.append(s)
    ans += s.count('AB')
    
    if s[-1] == 'A':
        right_A += 1 
    if s[0] == 'B':
        left_B += 1
        
ans += min(right_A, left_B)
print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
#d=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
#import numpy as np
#n=int(input())
#li=input().split()
#import fractions
#lis=list(map(int,input().split()))

n=int(input())
S=[]
ans=0
firstB,lastA,bothAB=0,0,0

for i in range(n):
    S.append(input())
    flag=0
    for j in range(len(S[-1])-1):
        if S[-1][j:j+2]=="AB":
            ans+=1
    if S[-1][0]=="B":
        firstB+=1
        flag+=1
    if S[-1][-1]=="A":
        lastA+=1
        flag+=1
    if flag==2:
        bothAB+=1
        firstB-=1
        lastA-=1

if firstB!=0 or lastA!=0:
    ans+=min(firstB,lastA)+bothAB
else:
    ans+=(bothAB-1)

print(ans)

Submission status: Wrong Answer

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

if a >= 0:
    if b >= 1 and c >= 1:
        ans += a-1+2+min(b-1,c-1)
    elif b >= 1 or c >= 1:
        ans += a
    else:
        ans += a-1
else:
    if b >= 1 and c >= 1:
        ans += min(b,c)
print(ans)

Submission status: Wrong Answer

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

cnt = 0
judge = 0
for i in range(n):
    for j in range(len(s[i])):
        if j != len(s[i]) - 1:
            if s[i][j] == "A":
                judge = 1
        if judge == 1 and s[i][j] != "A":
            if s[i][j] == "B":
                cnt += 1
                judge = 0
            else:
                judge = 0
        if j == len(s[i]) - 1:
            judge = 0
cnt_a = 0
cnt_b = 0
for i in range(n):
    len_s = len(s[i])
    if s[i][len_s - 1] == "A":
        cnt_a += 1
    if s[i][0] == "B":
        cnt_b += 1

print(cnt + min(cnt_a, cnt_b))

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

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
    try:
        ans += min(a, b)
    except ZeroDivisionError:
        pass
    p(ans)


main()

Submission status: Wrong Answer

Solution code:
Acnt = 0
Bcnt = 0
spcnt = 0
N = int(input())
s = [input() for i in range(N)]
string = "".join(s)
maincount = string.count("AB")
for i in s:
    if i[-1] == "A":
        Acnt += 1
for i in s:
    if i[0] == "B":
        Bcnt += 1
        if i[-1] == "A":
           spcnt += 1

print(maincount+min(Acnt,Bcnt)-1 if Bcnt == spcnt else maincount+min(Acnt,Bcnt))

Submission status: Wrong Answer

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

print(c + min(a,b))

Submission status: Wrong Answer

Solution code:
N = int(input())

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


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

Submission status: Wrong Answer

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

print(c + min(a, b))

Submission status: Wrong Answer

Solution code:
count = 0
aco = 0
bco = 0
abco = 0
l = []
n = int(input())
for i in range(n):
    s = input()
    l.append(s)
    count += s.count("AB")
    if s[0] == "B" :
        bco += 1
    if s[-1] == "A" :
        aco += 1
    if s[0] == "B" and s[-1] == "A" :
        abco += 1
if max(aco,bco) == abco and aco == bco :
    print(count+min(aco,bco)-1)
else :
    print(count+min(aco,bco))

Submission status: Wrong Answer

Solution code:
n = int(input())
ans = 0
last_a = 0
start_b = 0
sl_ba = 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
    if s.find("B") == 0 and s.rfind("A") == len(s) - 1:
        sl_ba += 1
ans += min(last_a, start_b)
if sl_ba >= 2 and last_a == 0 and start_b == 0:
    ans -= 1
print(ans)

Submission status: Wrong Answer

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

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

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

print(c)

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), N-1)

print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

ans = cnt_a = cnt_b = cnt_ab = 0
for s in S:
    ans += s.count("AB")
    if s[-1] == "A":
        cnt_a += 1
    if s[0] == "B":
        cnt_b += 1
    if s[0] == "B" and s[-1] == "A":
        cnt_ab += 1
if cnt_a == cnt_ab and cnt_b == cnt_ab:
    cnt_a -= 1
ans += min(cnt_a, cnt_b, N - 1)

print(ans)

Submission status: Wrong Answer

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

countAB = 0
firstB = 0
lastA = 0

for i in range(len(s)):
    if s[i][0] == 'B':
        firstB = firstB + 1
    if s[i][-1] == 'A':
        lastA = lastA + 1
    for j in range(len(s[i]) - 1):
        if s[i][j] == 'A' and s[i][j + 1] == 'B':
            countAB = countAB + 1

if firstB > lastA:
    print(countAB + lastA)
else:
    print(countAB + firstB)

Submission status: Wrong Answer

Solution code:
N = int(input())

ans = 0
dic = {"AB": 0, "A": 0, "B": 0}
for i in range(N):
    S = list(str(input()))
    pre = S[0]
    for j in range(1, len(S)):
        if (S[j-1] + S[j]) == "AB":
            ans += 1
    if S[-1] == "A" and S[0] == "B":
        dic["AB"] += 1
    elif S[-1] == "A":
        dic["A"] += 1
    elif S[0] == "B":
        dic["B"] += 1

# make pairs
ans += min(dic["A"], dic["B"])
ans += int(dic["AB"]/2)

# remain
remain = abs(dic["A"] - dic["B"])
if remain > 0:
    ans += 1

print(ans)

Submission status: Wrong Answer

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

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==BA:
    tmp4=0
elif tmp3==tmp2 and tmp2!=0:
    tmp4=(BA-tmp3)
elif tmp3==tmp2 and tmp2==0:
    tmp4=(BA-tmp3)-1
ans=ans+tmp+tmp3+tmp4
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = [input() for _ in range(N)]
num_a = 0
num_b = 0
num_ba = 0
num_ab = 0
for i in s:
    if(i[-1]=='A' and i[0]=='B'):
        num_ba += 1
    elif(i[-1]=='A'):
        num_a+=1
    elif(i[0]=='B'):
        num_b+=1
    last = ''
    for k in i:
        if(k=='A'):
            last = 'A'
        elif(last == 'A' and k=='B'):
            num_ab += 1
            last = ''
        else:
            last = ''
num_conn = min(num_a,num_b)
if(num_ba>0 and num_a!=num_b):
    print(num_ab+num_ba+num_conn)
else:
    print(num_ab+num_ba+num_conn-1)

Submission status: Wrong Answer

Solution code:
N = int(input())
S_tail_a_head_b = []
S_tail_a = []
S_head_b = []
S_ab = []
for _ in range(N):
    s = input()
    if s.find('AB') == -1 and s[0] != 'B' and s[-1] != 'A':
        continue
    elif s[0] == 'B' and s[-1] == 'A':
        S_tail_a_head_b.append(s)
    elif s[0] == 'B':
        S_head_b.append(s)
    elif s[-1] == 'A':
        S_tail_a.append(s)
    else:
        S_ab.append(s)

S = ''.join(S_ab)
head_b = ''
for i in range(max(len(S_head_b), len(S_tail_a))):
    if len(S_head_b) > i and len(S_tail_a) > i:
        S += S_tail_a[i] + S_head_b[i]
    elif len(S_head_b) <= i:
        S += ''.join(S_tail_a[i:])
        break
    else:
        head_b = ''.join(S_head_b[i:])
        break

S += ''.join(S_tail_a_head_b) + head_b

print(S.count('AB'))

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 and b_a==1:
    print(sum(count_list))
else:
    print(sum(count_list)+minimum)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
#C
N = int(input())
cnt = 0
headB, tailA = 0, 0
for _ in range(N):
    si = input()
    cnt += si.count('AB')
    if si[0] == 'B': headB += 1
    if si[-1] == 'A': tailA += 1
cnt += min(headB, tailA, N-1)
print(cnt)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
def solve():
    N = int(raw_input())
    S = []
    for i in range(N):
        S.append(raw_input())
    has_AB = 0
    end_byA = 0
    start_byB = 0
    for i in range(N):
        if S[i][0] == 'B':
            start_byB += 1
        if S[i][-1] == 'A':
            end_byA += 1
        for j in range(len(S[i]) - 1):
            if S[i][j:(j+2)] == 'AB':
                has_AB += 1
    ret = has_AB + min(end_byA, start_byB)
    print str(ret)

if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
n=int(input())
b_start=0
a_last=0
both=0
ans=0
for i in range(n):
    s=input()
    ans+=s.count("AB")
    if s[0]=="B":
        if s[len(s)-1]=="A":
            both+=1
        else:
            b_start+=1
    elif s[len(s)-1]=="A":
        a_last+=1
diff=abs(b_start-a_last)
if diff <= both:
    print(min(b_start,a_last)+both+ans)
else:
    print(max(b_start,a_last)+(both-diff)//2+ans)

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)-1):
        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 sys

readline = sys.stdin.readline

N = int(readline())
S_list = [readline().rstrip() for i in range(N)]

count = 0
head_B = 0
tail_A = 0
AxB = 0
for s in S_list:
    for i in range(len(s)):
        if s[i:i+2] == 'AB':
            count += 1
    if s[0] == 'B':
        head_B += 1
    if s[-1] == 'A':
        tail_A += 1
    if s[0] == 'B' and not (s[-1] == 'A'):
        AxB += 1

if head_B == tail_A:
    if AxB > 0:
        print(count + head_B)
    else:
        print(count + head_B - 1)
else:
    print(count + min(head_B, tail_A))

Submission status: Wrong Answer

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

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

cnt += both_num - 1
head_b_num -= both_num
tail_a_num -= both_num
if head_b_num > 0:
  cnt += 1
  head_b_num -= 1
if tail_a_num > 0:
  cnt += 1
  tail_a_num -= 1

cnt += min(head_b_num,tail_a_num)
  
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[0] == 'A' or temp[-1] == 'A':
        a_parts += 1
    if temp[0] == 'B' or temp[-1] == 'B':
        b_parts += 1
if a_parts < b_parts:
    counter += a_parts
else:
    counter += b_parts
print(counter)

Submission status: Wrong Answer

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

    for j in range(len(a[i]) - 1):

        if a[i][j] == "B" and flag:
            cnt += 1
        else:
            flag = False

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

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

Submission status: Wrong Answer

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

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
    if a==b:
        return a-1
    else:
        
        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:
from collections import defaultdict
N = int(input())
S = [None] * N
cnt = 0
B_X = 0
X_A = 0
B_A = 0

for i in range(N):
  S[i] = input()
  cnt += S[i].count('AB')
  left_B_frag = S[i][0] == 'B'
  right_A_flag = S[i][-1] == 'A'
  if left_B_frag and right_A_flag:
    B_A += 1
  elif left_B_frag:
    B_X += 1
  elif right_A_flag:
  	X_A += 1

if B_A >= 2:
  cnt += B_A - 1
  B_A = 1
if B_X > X_A:
  cnt += X_A + min(B_A, B_X-X_A)
else:
  cnt += B_X + min(B_A, X_A-B_X)
# print(B_A, B_X, X_A)
print(cnt)

Submission status: Wrong Answer

Solution code:
import sys


fin = sys.stdin.readline
N = int(fin())
s_list = [fin().rstrip("\n") for _ in range(N)]
num_AB_in_between = 0
s_Bhoge = 0
s_hogeA = 0
s_BA = 0
for s in s_list:
    if s[0] == "B" and s[-1] == "A":
        s_BA += 1
    elif s[0] == "B":
        s_Bhoge += 1
    elif s[-1] == "A":
        s_hogeA += 1

    for i, char in enumerate(s[:-1]):
        next_char = s[i + 1]
        if char == "A" and next_char == "B":
            num_AB_in_between += 1

# print(s_Bhoge, s_hogeA, s_BA)
if s_BA:
    num_AB_bound = 2 * s_BA - 2 + int(s_Bhoge > 0) + int(s_hogeA > 0)
    num_AB_bound += max(0, min(s_Bhoge - 1, s_hogeA - 1))
    # num_AB_bound += min(s_Bhoge - 1, s_hogeA - 1)
else:
    num_AB_bound = min(s_Bhoge, s_hogeA)
print(num_AB_in_between + num_AB_bound)

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


if end_A != 0 or eni_B != 0:
    count = count + min(end_A,eni_B) + both
    print(count)
else :
    print(count)

Submission status: Wrong Answer

Solution code:
import sys
import collections
ns = lambda: sys.stdin.readline().rstrip()
ni = lambda: int(ns())
nm = lambda: map(int, sys.stdin.readline().split())
nl = lambda: list(nm())
nsm = lambda: map(str, sys.stdin.readline().split())

n = ni()
s = []
ca = 0
cb = 0
ans = 0
both = 0
for i in range(n):
    t = ns()
    if t[0] == 'B' and t[-1] != 'A':
        cb += 1
    elif t[-1] == 'A' and t[0] != 'B':
        ca += 1
    elif t[0] == 'B' and t[-1] == 'A':
        both += 1
    for j in range(1, len(t)):
        if t[j - 1] == 'A' and t[j] == 'B':
            ans += 1
if both > 0:
    ans += both - 1
ans += min(ca, cb)
if both > 0 and abs(ca - cb) > 0:
    ans += 1
print(ans)

Submission status: Wrong Answer

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

IB= [0] * (N)
LA = [0] * (N)
flag = True
cntb= 0
cnta = 0
ans = 0
for i in range(N):
    if S[i][0] == 'B':
        IB[i] = 1
        cntb += 1
    if S[i][len(S[i])-1] == 'A' :
        LA[i] = 1
        cnta += 1
    if (IB[i] == 1 and LA[i] == 0) or (IB[i]==0 and LA[i] == 1):
        flag = False
    for j in range(len(S[i])-1):
        if S[i][j] == 'A' and S[i][j+1]=='B' : ans += 1
        
        
ans += min(cntb,cnta)
if flag:    
    ans -= 1



print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [input() for _ in range(N)]
ans = 0
a = 0
b = 0
ab = 0
for s in S:
    if s[0] == "B" and s[-1] == "A":
        ab += 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
if ab >= 1:
    ans += max(ab-1, 0)
    if a > b:
        b += 1
    elif a == b:
        a += 1
        b += 1
    else:
        a += 1
ans += min(a, b)
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
	N = int(input())
	S = [""]*N
	ans = 0
	a_end = 0
	b_begin = 0
	a_end_b_begin = 0
	for i in range(N):
		S[i] = input()
		if "AB" in S[i]:
			ans += S[i].count("AB")
		if S[i][0] == "B":
			if S[i][-1] == "A":
				a_end_b_begin += 1
				continue
			b_begin += 1
		if S[i][-1] == "A":
			a_end += 1
	ans += min(b_begin, a_end)
	ans += min(abs(b_begin-a_end), a_end_b_begin)
	dif = a_end_b_begin - abs(b_begin-a_end)
	if dif > 0:
		ans += dif

	print(ans)


if __name__ == '__main__':
	main()

Submission status: Wrong Answer

Solution code:
n = int(input())
sl = [input() for _ in range(n)]
sb,la,cnt,both = 0,0,0,0
for s in sl:
  cnt += s.count("AB")
  if s[0] == "B":
    sb += 1
  if s[-1] == "A":
    la += 1
  if [-1] == "A" and s[0] == "B":
    both += 1
if sb == la == both:
  cnt -= 1
print(cnt + min(la,sb))

Submission status: Wrong Answer

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

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

if a>b :
    print(ab+b)
else: 
    print(ab+a)

Submission status: Wrong Answer

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

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

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

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

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

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

    print(count)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
N=int(input())
XA=0
BA=0
BX=0
internalAB=0
for t in range(N):
    i=input()
    headUsed=False
    footUsed=False
    for x,j in enumerate(i):
        if x==len(i)-1:break
        if j=="A" and i[x+1]=="B":
            internalAB+=1
            if x==0:headUsed=True
            if x==len(i)-2:footUsed=True
    if i[0]=="B" and not headUsed:
        if i[-1]=="A" and not footUsed:
            BA+=1
        else:BX+=1
    elif i[-1]=="A" and not footUsed:
        XA+=1
ans=internalAB+BA+min(XA,BX)
if XA==BX==0:ans-=1
print(ans)

Submission status: Wrong Answer

Solution code:
if __name__ == '__main__':
    import sys
    input = sys.stdin.readline

    n = int(input())
    top = 0
    bottom = 0
    top_and_bottom = 0
    ans = 0
    for _ in range(n):
        sentence = input().rstrip()
        ans += sentence.count("AB")
        if sentence[0] == "B":
            top += 1
            if sentence[-1] == "A":
                top_and_bottom += 1
        if sentence[-1] == "A":
            bottom += 1
    if top == top_and_bottom and top_and_bottom == bottom:
        print(ans+top-1)
    else:
        print(ans+min([top, bottom]))

Submission status: Wrong Answer

Solution code:
N = int(input())
s = [0 for i in range(N)]
for i in range(N):
    s[i] = input()
count = 0
Aowari = 0
Bhazimari = 0
ABtomoni = 0
for i in range(N):
    count += s[i].count('AB')
    if s[i][-1] == 'A' and s[i][0] == 'B':
        ABtomoni += 1
    elif s[i][-1] == 'A':
        Aowari += 1
    elif s[i][0] == 'B':
        Bhazimari += 1
if ABtomoni > 0:
    if Aowari >0 and Bhazimari >0:
        count += ABtomoni+1
        Aowari -= 1
        Bhazimari -= 1
    elif Aowari > 0 and Bhazimari == 0:
        count += ABtomoni
        Aowari -= 1
    elif Aowari == 0 and Bhazimari > 0:
        count += ABtomoni
        Bhazimari -= 1
count += min(Aowari, Bhazimari)
print(count)

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 ab >= 2:
    print(ans+ab-1+max(min(a+1,b),min(a,b+1)))
elif ab == 1:
    print(ans+max(min(a+1,b),min(a,b+1)))
else:
    print(ans+min(a,b))

Submission status: Wrong Answer

Solution code:
n =  int(input())
a,b,c,d = 0,0,0,0
for _ in [0]*n:
  s = input()
  if s[0] == "B" and  s[-1] == "A":
    d += 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":
      c += 1
if a == 0 and b == 0:
  c += d-1
else:
   c += d + min(a,b)
print(c)

Submission status: Wrong Answer

Solution code:
n = int(input())

count = 0
bstart = 0
aend = 0
for _ in range(n):
    si = input()
    if si[0] == 'B':
        bstart += 1
    if si[-1] == 'A':
        aend += 1
    for i in range(len(si)-1):
        if si[i] == 'A' and si[i+1] == 'B':
            count += 1

count += min(bstart, aend)

print(count)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
a = 0
b = 0
ins = 0
data = ""
for i in range(n):
    data = ""
    t = input()
    k = t.split("AB")
    for p in k:
        data += p
    #print(t[0], data[0], t[-1], data[-1], t)
    if len(data) == 0:
        pass
    elif data[0] == "B" and t[0] == data[0]:
        b+=1
    if len(data) == 0:
        pass
    elif data[-1] == "A" and t[-1] == data[-1]:
        a+=1
    ins += int((len(t)-len(data))/2)
    #print(ins)
print(min(a, b)+ins)