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:
# coding:utf-8


def main():
    N = int(input())
    s_list = []
    for i in range(N):
        s_list.append(input().rstrip())

    ans = 0
    a_last = 0
    b_start = 0
    for si in s_list:
        if si[0] == "B":
            b_start += 1
        if si[-1] == "A":
            a_last += 1
        for i in range(len(si)-1):
            if si[i] == "A" and si[i+1] == "B":
                ans += 1

    ans = ans + min(a_last, b_start)

    print(ans)


if __name__ == "__main__":
    main()

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:
            p(res)
            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:
N= int(input())

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

print(ans + min(a,b))

Submission status: Wrong Answer

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

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

Submission status: Wrong Answer

Solution code:
N = int(input())
P = 0
K = 0
L = 0
ans = 0
for _ in range(N):
  s = input()
  lis = []
  for i in range(len(s) - 1):
    lis.append(s[i:i+2])
    num = lis.count("AB")
  ans += num
  if s[0] == "B" and s[-1] == "A":
    P += 1
  elif s[0] == "B":
    K += 1
  elif s[-1] == "A":
    L += 1
if P >= 1:
  ans += (P - 1)
  ans += min(K, L)
  if K != L:
    ans += 1
else:
  ans += min(K, L)
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
count=0
bx=0
xa=0
ba=0
for i in range(n):
    s=input()
    for j in range(0,len(s)-1):
        if s[j:j+2]=='AB':
            count=count+1
    if s[0]=='B' and s[len(s)-1]=='A':
        ba=ba+1
    if s[0]=='B' and not s[len(s)-1]=='A':
        bx=bx+1
    if not s[0]=='B' and s[len(s)-1]=='A':
        xa=xa+1
print(count,bx,xa,ba)
if bx==0 and xa==0:
    if ba>=2:
        count=count+ba-1
else:
    count=count+ba+min(xa,bx)
print(count)

Submission status: Wrong Answer

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

for i in range(N):
    S=str(input())
    s=len(S)
    if S[0]=="B" and S[s-1]=="A":
        a+=1
    elif S[0]=="B":
        b+=1
    elif S[s-1]=="A":
        c+=1
    for i in range(s-1):
        if S[i]=="A" and S[i+1]=="B":
            d+=1


b=max(b,c)
c=min(b,c)

e=b-c

if e>=a:
    print(a+c+d)
else:
    print(a-1+c+d)

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==1 and ctr_b==1 and ctr_ab==1:
    print(ctr)
else:
    print(ctr+min(ctr_a,ctr_b))

Submission status: Wrong Answer

Solution code:

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

A = 0
B = 0
BA = 0
cnt = 0
for i in s:
    if i.startswith("B"):
        B += 1
    if i.endswith("A"):
        A += 1
    if i.startswith("B") and i.endswith("A"):
        BA += 1
    for j in range(1,len(i)):
        if i[j-1] + i[j] == "AB":
            cnt += 1

if BA == 0:
    print(min(A,B)+cnt)
else:
    if min(A,B) == 1:
        print(A+B+cnt)
    else:
        print(min(A,B)+cnt)

Submission status: Wrong Answer

Solution code:
N=int(input())
s_list = [input() for i in range(N)]
AB_count = sum(map(lambda s: s.count('AB'), s_list))
tail_A = sum(map(lambda s: s[-1]=='A', s_list))
head_B = sum(map(lambda s: s[0]=='B', s_list))
print(AB_count + min(tail_A, head_B))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
INF = float("inf")


def solve(N: int, s: "List[str]"):
    ABcount = 0
    Aend = 0
    Bstart = 0
    AendBstart = 0
    for i in range(N):
        if "AB" in s[i]:
            ABcount += 1
        if s[i][0] == "B":
            if s[i][-1] == "A":
                AendBstart += 1
            else:
                Bstart += 1
        elif s[i][-1] == "A":
            Aend += 1

    ABcount += min(Aend, Bstart)
    if abs(Aend - Bstart) > 0:
        ABcount += AendBstart
    else:
        ABcount += max(AendBstart-1, 0)
    print(ABcount)

    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    s = [next(tokens) for _ in range(N)]  # type: "List[str]"
    solve(N, s)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

answer=0
a=0
b=0
q=1
for t in s:
    for i in range(0,len(t)-1):
        if t[i]=="A" and t[i+1]=="B":
            answer+=1
    if t[0]=="B":
        b+=1
    if t[-1]=="A":
        a+=1
    if (t[0]=="B" and t[-1]!="A") or (t[0]!="B" and t[-1]=="A"):
        q=0

if a>b:
    print(answer+b-q)
else:
    print(answer+a-q)

Submission status: Wrong Answer

Solution code:
n = int(input())
cnt = 0
s0b = 0
sla = 0
s0bsla = 0
for i in range(n):
    s = input()
    cnt += s.count("AB")
    if s[0] == "B" and s[-1] != "A":
        s0b += 1
    elif s[0] != "B" and s[-1] == "A":
        sla += 1
    elif s[0] == "B" and s[-1] == "A":
        s0bsla += 1
if s0bsla > 0:
    cnt += s0bsla - 1
if sla > 0:
    cnt += 1
    sla -= 1
if s0b > 0:
    cnt += 1
    s0b -= 1
cnt += min(s0b, sla)
print(cnt)

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

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

	
	
if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
N=int(input())
s=' '
num_AB=0
num_A=0
num_B=0
for i in range(0,N):
    s=str(input())
    if(s[0]=='B'):
        num_B+=1
    if(s[-1]=='A'):
        num_A+=1
    for j in range(0,len(s)-1):
        if(s[j]=='A' and s[j+1]=='B'):
            num_AB+=1;
ans=num_AB+min(num_A,num_B)
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
max_AB = max(count_last_A, count_first_B)
min_AB = min(count_last_A, count_first_B)
if max_AB - min_AB > count_both:
    temp = count_both
else:
    temp = min_AB + count_both + (count_both - max_AB + min_AB) // 2
print(count_AB + temp)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
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':
    sB += 1
  if s[-1] == 'A':
    eA += 1
  if s[0] == 'B' and s[-1] == 'A':
    both += 1

ans = inAB + min(sB, eA)
if both == sB == eA:
  ans -= 1
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())

ans = 0
aEnd = 0
bStart = 0
abBoth = 0
for _ in range(N):
    s = input()
    if s[0] == "B":
        bStart += 1
    if s[-1] == "A":
        aEnd += 1
        if s[0] == "B":
            abBoth += 1

    for i in range(len(s) - 1):
        if s[i:i+2] == "AB":
            ans += 1

ans += min(aEnd, bStart)
if abBoth == aEnd == bStart:
    ans -= 1

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
cnt = 0
endA = 0
startB = 0
both = 0
for i in range(N):
	s = input()
	flgA = s[-1] == "A"
	flgB = s[0] == "B"
	if flgA and flgB:
		both += 1
	elif flgA:
		endA += 1
	elif flgB:
		startB += 1
	cnt += s.count("AB")

cnt += both - 2
if endA > 0:
	cnt += 1
	endA -= 1
if startB > 0:
	cnt += 1
	startB -= 1
cnt += min(endA, startB)
print(cnt)

Submission status: Wrong Answer

Solution code:


def read_input():
    n = int(input())
    slist = []
    for i in range(n):
        slist.append(input())

    return n, slist

def submit():
    n, slist = read_input()

    ab_in = 0
    x_a = 0
    b_x = 0
    b_a = 0

    for s in slist:
        if 'AB' in s:
            ab_in += 1

        if s[0] == 'B' and s[-1] == 'A':
            b_a += 1
        elif s[0] == 'B':
            b_x += 1
        elif s[-1] == 'A':
            x_a += 1

    pure_match = min(b_x, x_a)

    if b_a == 0:
        print(ab_in + pure_match)
        return

    # b_xやx_aはあまっていないので、b_a同士でペアを作る
    if b_x == x_a:
        print(ab_in + pure_match + b_a - 1)
    else:
        # b_xやx_aがあまっているので、左右どちらかにb_aをつなげる
        print(ab_in + pure_match + b_a)


if __name__ == '__main__':
    submit()

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

print(numAB + min(numinitB, numlastA))

Submission status: Wrong Answer

Solution code:
N=int(input())
s=[]
for i in range(N):
    s.append(input())
a=[0]*N
b=[0]*N
c=[0]*N
for i in range(N):
    a[i]=s[i].count('AB')
    if s[i][-1]=='A':
        b[i]=1
    else:
        pass
    if s[i][0]=='B':
        c[i]=1
B=sum(b)
C=sum(c)
D=min(B,C)
if min(B,C)==N:
    D=N-1
else:
    pass
print(sum(a)+ D)

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 min(A_end_cnt,B_start_cnt) == AB_cnt:
    ans -= 1
print(ans)

Submission status: Wrong Answer

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


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

    # if(min(a,b)+x < max(a,b)):
    #     ans1 = min(max(a,b),min(a,b)+x)
    # else:
    #     ans1 = (a+b+x)//2
    
    # # ans1 = min(min(a,b)+x,)

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


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

    print(ans1+ans2)
    
    return


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

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
x = int(input())
a = 0
b = 0
c = 0
f = 0
bun = []
for p in range(x):
    bun = input()
    if bun[0] == "B":
        b +=1
    if bun[len(bun)-1] == "A":
        a += 1
        if bun[0] == "B":
            f += 1
    for k in range(len(bun)-1):
        if bun[k] == "A":
            if bun[k+1] == "B":
                c += 1




if f == a:
    a -= 1
if a < b:
    print(a+c)
else:
    print(b+c)

Submission status: Wrong Answer

Solution code:
N = int(input())

AB_count = 0
A_end = 0
B_start = 0
B_start_and_A_end = 0
for i in range(N):
    string = input()
    AB_count += string.count("AB")
    
    if string[0] == "B":
        B_start += 1
    if string[-1] == "A":
        A_end += 1
    if string[0] == "B" and string[-1] == "A":
        B_start_and_A_end += 1
    
new_AB = min(A_end,B_start)
if B_start_and_A_end == A_end and B_start_and_A_end == B_start:
    new_AB -= 1

print(AB_count+new_AB)

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[-1]=='A':
        a+=1
    if s[0]=='B':
        b+=1
if a>b:
    print(ans+b)
else:
    print(ans+a)

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 += 1
		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())
ss = [input() for i in range(n)]
ans = 0
a,b = 0,0
for s in ss:
    ans += s.count('AB')
    if s[0] is 'B':
        a += 1
    if s[-1] is 'A':
        b += 1
print(ans+min(a,b))

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 and eni_B != 0:
    count = count + min(end_A,eni_B) + both
    print(count)
else :
    print(count)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n = int(input())


cnt_ba = 0
cnt_a = 0
cnt_b = 0
ans = 0
for i in range(n):
      s = input()
      ans += s.count("AB")
      if s[0] == "B" and s[-1] == "A":
            cnt_ba += 1
      elif s[0] == "B":
            cnt_b += 1
      elif s[-1] == "A":
            cnt_a += 1
if n != 1:
      print(ans + min(cnt_a+cnt_ba, cnt_b+cnt_ba))
else:
      print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
c = [0, 0, 0]
ans = 0
for i in range(n):
    si = input()
    ans += si.count('AB')
    if si[0] == 'B' and si[-1] == 'A':
        c[0] += 1
    elif si[0] == 'B':
        c[1] += 1
    elif si[-1] == 'A':
        c[2] += 1
    s.append(si)
ans += max(0, c[0] - 1)
if c[1] >= 1 and c[2] >= 1:
    if c[0] > 0 and abs(c[1] - c[2]) > 0:
        ans += 1
    ans += min(c[1], c[2])
elif c[1] >= 1 and c[0] > 0:
    ans += 1
elif c[2] >= 1 and c[0] > 0:
    ans += 1
print(ans)

Submission status: Wrong Answer

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



def main(s):
    SB = [si for si in s if si[0] == 'B']
    SR = [si for si in s if si[0] != 'B']
    if SR:
        R = [SR.pop()]
    else:
        R = [SB.pop()]
    while SR or SB:
        if SR and SB:
            if R[-1][-1] == 'A':
                R.append(SB.pop())
            else:
                R.append(SR.pop())
        elif SR:
            R.append(SR.pop())
        elif SB:
            R.append(SB.pop())
    return "".join(R).count("AB")


print(main(s))

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")
    if S[i].startswith("B"):
        a += 1
    if S[i].endswith("A"):
        b += 1
cnt += min(a, b)
print(cnt)

Submission status: Wrong Answer

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

for i in range(N):
    S=str(input())
    s=len(S)
    if S[0]=="B" and S[s-1]=="A":
        a+=1
    elif S[0]=="B":
        b+=1
    elif S[s-1]=="A":
        c+=1
    for i in range(s-1):
        if S[i]=="A" and S[i+1]=="B":
            d+=1
print(a,b,c,d)

b=max(b,c)
c=min(b,c)

e=b-c

if e>=a:
    print(a+c+d)
else:
    print(a-1+c+d)

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

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] == "B":
        b += 1
    if s[i][-1] == "A":
        a += 1
print(c + min(a, b))

Submission status: Wrong Answer

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

cnt = 0
cntA = 0
cntB = 0

for s in S :
    for i in range(1, len(s)) :
        if s[i - 1] =='A' and s[i] == 'B':
            cnt += 1
    if s[0] == 'B' :
        cntA += 1
    if s[len(s) - 1] == 'A' :
        cntB += 1

print(cnt + min(cntA, cntB))

Submission status: Wrong Answer

Solution code:
N = int(input())

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

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

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 += 0
    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 min(A_end_cnt,B_start_cnt) == AB_cnt:
    ans -= 1
print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n = int(input())
S = [input() for _ in range(n)]
cnt = 0
fb_cnt = 0
ba_cnt = 0
for s in S:
    idx = len(s) - 1
    for i in range(idx - 1):
        if s[i] == 'A' and s[i + 1] == 'B':
            cnt += 1
    if s[idx] == 'A':
        ba_cnt += 1
    if s[0] == 'B':
        fb_cnt += 1

print(cnt + min(fb_cnt, ba_cnt))

Submission status: Wrong Answer

Solution code:
n= int(input())
a = 0
b = 0
ab = 0
for i in range(n):
    s = input()
    for j in range(len(s)-1):
        if s[j] == "A" and s[j+1] == "B":
            ab+=1
    if s[len(s)-1] == "A":
        a += 1
    if s[0] == "B":
        b += 1
if a == b and a == 0:
    print(ab)
elif a != b:
    print(ab + min(a,b))
elif a == b:
    print(ab + a -1)

Submission status: Wrong Answer

Solution code:
def find_ab(s):
	tmp = 0
	for i in range(len(s) - 1):
		if s[i] == "A" and s[i + 1] == "B":
			tmp += 1
	return tmp

n = int(input())
ss = [list(input()) for _ in range(n)]

ans = 0
d = {"A":0, "B":0, "BA":0}
for s in ss:
	ans += find_ab(s)
	if s[0] == "B":
		if s[-1] == "A":
			d["BA"] += 1
		else:
			d["B"] += 1
	elif s[-1] == "A":
		d["A"] += 1

#print(ans, d)
if d["BA"] == 0:
	ans += min(d["A"], d["B"])
elif d["A"] == d["B"] == 0:
	ans += d["BA"] - 1
elif d["A"] == d["B"]:
	ans += d["BA"] - 1 + min(d["A"], d["B"])
else:
	ans += d["BA"] + min(d["A"], d["B"])

print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    from sys import stdin, stdout

    def read():
        return stdin.readline().rstrip('\n')

    def read_array(sep=None, maxsplit=-1):
        return read().split(sep, maxsplit)

    def read_int():
        return int(read())

    def read_int_array(sep=None, maxsplit=-1):
        return [int(a) for a in read_array(sep, maxsplit)]

    def write(*args, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in args) + end)

    def write_array(array, **kwargs):
        sep = kwargs.get('sep', ' ')
        end = kwargs.get('end', '\n')
        stdout.write(sep.join(str(a) for a in array) + end)

    n = read_int()
    b_starts = 0
    a_ends = 0
    both = 0
    count = 0

    for i in range(n):
        word = read()
        for i in range(1, len(word)):
            if word[i-1] == 'A' and word[i] == 'B':
                count += 1

        if word[0] == 'B' and word[-1] == 'A':
            both += 1
        elif word[-1] == 'A':
            a_ends += 1
        elif word[0] == 'B':
            b_starts += 1

    if a_ends > 0 and b_starts > 0:
        count += both + 1
        a_ends -= 1
        b_starts -= 1
    elif a_ends > 0:
        count += both
        a_ends -= 1
    elif b_starts > 0:
        count += both
        b_starts -= 1
    else:
        count += both - 1
    count += min(a_ends, b_starts)

    write(count)

main()

Submission status: Wrong Answer

Solution code:
# N = int(input())
# A = [int(x) for x in input().split()]
# from collections import defaultdict
# dd = defaultdict(lambda: 0)

N = int(input())

S = []
bStart = 0
aEnd = 0
ba = 0
abSum = 0
for i in range(N):
    s = input()
    abSum += s.count('AB')

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

ret = abSum + min(bStart,aEnd)
if ba > 0:
    ret += ba - 1
if bStart != aEnd:
    ret += 1

print(ret)

Submission status: Wrong Answer

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

ans = 0
for ss in sss:
    ans += ss.count('AB')

num_A = numB_ = numBA = 0
for ss in sss:
    is_A = ss.endswith('A')
    isB_ = ss.startswith('B')
    if is_A:
        if isB_:
            numBA += 1
        else:
            num_A += 1
    else:
        if isB_:
            numB_ += 1

ans += numBA - 1
if num_A > 0:
    ans += 1
    num_A -= 1
if numB_ > 0:
    ans += 1
    numB_ -= 1

ans += min(num_A, numB_)

print(ans)

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' and s[-1] ==  'A':
        AB += 1
    elif s[0] == 'B':
        B += 1
    elif s[-1] == 'A':
        A += 1

if max(A,B) - min(A,B) >= AB:
    additional = min(A,B) + AB
    print(ans + min(additional, N-1))
else:
    AB -= max(A,B) - min(A,B)
    additional = max(A,B) + AB//2
    print(ans + min(additional, N-1))

Submission status: Wrong Answer

Solution code:
def task_c():
    n = int(input())
    sss = [input().strip() for _ in range(n)]
    
    c_first_b = len([ss for ss in sss if ss[:1] == 'B'])
    c_last_a = len([ss for ss in sss if ss[-1:] == 'A'])
    c_fb_la = len([ss for ss in sss if ss[:1] == 'B' and ss[-1:] == 'A'])
    c_include_ab = len([ss for ss in sss if 'AB' in ss])
    c = min(c_first_b, c_last_a)
    if c_first_b == c_last_a and (c_fb_la == c_first_b or c_fb_la == c_last_a):
        c -= 1
    c += c_include_ab
    print(c)
    
task_c()

Submission status: Wrong Answer

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

cnt = 0
enda = 0
startb = 0
ba = 0
for s in strs:
    cnt += s.count("AB")
    enda += 1 if (s[-1] == "A") else 0
    startb += 1 if (s[0] == "B") else 0
    ba += 1 if (s[-1] == "A" and s[0] == "B") else 0

cnt -= 1 if (enda-ba == 0 and startb-ba == 0) else 0

print(cnt + min(enda, startb))

Submission status: Wrong Answer

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

cnt += min(a, b)

print(max(0, 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 += 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())
S = []
A, B, AB = 0, 0, 0
for i in range(N):
    a = input()
    S.append(a)
    if a[0] == 'B':
        B += 1
    if a[-1] == 'A':
        A += 1
    AB += a.count('AB')

print(AB + min(A, B))