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: Accepted

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

cnt = 0
for i in range(n):
    cnt += s[i].count("AB")
cnt_a = 0
cnt_b = 0
cnt_ab = 0
for i in range(n):
    len_s = len(s[i])
    if s[i][0] == "B" and s[i][len_s - 1] == "A":
        cnt_ab += 1
    elif s[i][len_s - 1] == "A":
        cnt_a += 1
    elif s[i][0] == "B":
        cnt_b += 1
if cnt_a == cnt_b == 0 and cnt_ab > 0:
    print(cnt + cnt_ab - 1)
else:
    print(cnt + min(cnt_a, cnt_b) + cnt_ab)

Submission status: Accepted

Solution code:
n=int(input())
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" 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
if a+k==0:
    print(max(c+d-1,c))
elif a+k>0:
    print(c+min(d+a,d+k))
else:
    print(c+min(a,k))

Submission status: Accepted

Solution code:
N = int(input())
BA = BX = XA = ans = 0
for _ in range(N):
    s = input()
    for i in range(len(s)-1):
        if s[i:i+2] == "AB":
            ans += 1
    if s[0] == "B" and s[-1] == "A":
        BA += 1
    elif s[0] == "B":
        BX += 1
    elif s[-1] == "A":
        XA += 1
ans += min(BX, XA) + (BA if (BX+XA) else max(BA-1, 0))
print(ans)

Submission status: Accepted

Solution code:
# In[1]:


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


# In[2]:


def countAB(string):
    cnt=0
    for i in range(len(string)-1):
        if string[i]+string[i+1]=="AB":
            cnt+=1
    return cnt


# In[3]:


def endA(string):
    if string[-1]=="A" and string[0]!="B":
        return 1
    else: return 0
def initB(string):
    if string[0]=="B" and string[-1]!="A":
        return 1
    else: return 0
def endAinitB(string):
    if string[0]=="B" and string[-1]=="A":
        return 1
    else: return 0


# In[4]:


simple_AB=0
Aend=0
Binit=0
eAiB=0
for s_tmp in s:
    simple_AB+=countAB(s_tmp)
    Aend+=endA(s_tmp)
    Binit+=initB(s_tmp)
    eAiB+=endAinitB(s_tmp)
if Aend+Binit>0:
    print(simple_AB+min(Aend, Binit)+eAiB)
elif Aend+Binit==0 and eAiB>0:
    print(simple_AB+eAiB-1)
else: print(simple_AB)

Submission status: Accepted

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

import sys
import copy

sys.setrecursionlimit(1000000)

# input = sys.stdin.readline

# ~~~~~~~~~~~~~~~~~~~~~_(＾～＾ ｣ ∠)_~~~~~~~~~~~~~~~~~~

N = int(input())

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

ans = 0

for i in range(N):
    for j in range(len(S[i]) - 1):
        if S[i][j] == 'A' and S[i][j + 1] == 'B':
            ans += 1

a = 0
b = 0
ba = 0

for i in range(N):
    if S[i][0] == 'B' and S[i][-1] == 'A':
        ba += 1
    elif S[i][0] == 'B' and S[i][-1] != 'A':
        b += 1
    elif S[i][0] != 'B' and S[i][-1] == 'A':
        a += 1

exist = False

if a > 0 or ba > 0:
    exist = True
    if a > 0:
        a -= 1
    elif ba > 0:
        ba -= 1

if exist:
    ans += ba
    if b > 0:
        b -= 1
        ans += 1
    ans += min(a, b)

print(ans)

Submission status: Accepted

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

m = min(end_A,eni_B)
M = max(end_A,eni_B)

if both == 0 :
    count = count + m
else:
    if m == 0 and M == 0 :
        count = count + both - 1
    else:
        count = count + both + m 

print(count)

Submission status: Accepted

Solution code:
n=int(input())
s=[0]*n
ct=0
a=0
b=0
c=0
for i in range(n):
    s[i]=input()
for i in range(n):
    for j in range(len(s[i])):
        t=s[i]
        ts=list(t)
        ts.append(0)
        if ts[j]=='A' and ts[j+1]=='B':
            ct+=1
    if ts[0]=='B' and ts[len(s[i])-1]!='A':
        a+=1
    if ts[len(s[i])-1]=='A' and ts[0]!='B':
        b+=1
    if ts[0]=='B' and ts[len(s[i])-1]=='A':
        c+=1
ct += max(0,c -1)
if c !=0:
  if a > 0 and b >0:
    ct += 2 + min(a-1,b-1)
  elif a>0:
    ct += 1 + min(a-1,b)
  elif b>0:
    ct += 1 + min(a,b-1)
else:
  ct += min(a,b)
print(ct)

Submission status: Accepted

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

# 先頭が B ではなく、末尾が A な文字列
TxBA = [s[n] for n in range(N) if s[n][0] != "B" and s[n][-1] == "A"]

# 先頭が B で、末尾が A な文字列
TBBA = [s[n] for n in range(N) if s[n][0] == "B" and s[n][-1] == "A"]

# 先頭が B で、末尾が A ではない文字列
TBBx = [s[n] for n in range(N) if s[n][0] == "B" and s[n][-1] != "A"]

# 上記を除き中に "AB" が存在する文字列
kouho = TxBA + TBBA + TBBx
ss = s.copy()
for k in kouho:
    ss.remove(k)
    
str = ""
while (len(TxBA)):
    str += TxBA.pop()
    while (len(TBBA)):
        str += TBBA.pop()
    if (len(TBBx)):
        str += TBBx.pop()

while (len(TBBA)):
    str += TBBA.pop()
if (len(TBBx)):
    str += TBBx.pop()

while (len(TBBx)):
    str += TBBx.pop()

while (len(ss)):
    str += ss.pop()

print(str.count("AB"))

Submission status: Accepted

Solution code:
n=int(input())
s=[0]*n
ct=0
a=0
b=0
c=0
for i in range(n):
    s[i]=input()
for i in range(n):
    for j in range(len(s[i])):
        t=s[i]
        ts=list(t)
        ts.append(0)
        if ts[j]=='A' and ts[j+1]=='B':
            ct+=1
    if ts[0]=='B' and ts[len(s[i])-1]!='A':
        a+=1
    if ts[len(s[i])-1]=='A' and ts[0]!='B':
        b+=1
    if ts[0]=='B' and ts[len(s[i])-1]=='A':
        c+=1
if max(a,b)>0 or c==0:
    print(ct+min(a,b)+c)
elif max(a,b)==0:
    print(ct+c-1)

Submission status: Accepted

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

res = 0
counta = 0
countb = 0
countab = 0

for s in S:
    res += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        countab += 1
    elif s[0] == "B":
        countb += 1
    elif s[-1] == "A":
        counta += 1

if counta + countb == 0:
    res += max(0, countab - 1)
else:
    res += countab + min(counta, countb)

print(res)

Submission status: Accepted

Solution code:
import re

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

tmp = 0

B_A = 0
B_any = 0
any_A = 0

for i in range(N):
    tmp = tmp + s[i].count("AB")
    if s[i][0:1] == "B":
        if s[i][-1:] == "A":
            B_A = B_A + 1
        else:
            B_any = B_any + 1
    elif s[i][-1:] == "A":
        any_A = any_A + 1

add = 0

add1 = min(B_any,any_A)

add = max(B_A - 1,0)


if B_any + any_A > 0:
    if B_A >= 1:
        add1 = add1 + 1

print(tmp+add+add1)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def solve(N, Ss):
    a = 0
    b = 0
    both = 0
    ans = 0
    for s in Ss:
        ans += s.count("AB")
        if s[-1] == "A" and s[0] == "B":
            both += 1
        else:
            if s[-1] == "A":
                a += 1
            if s[0] == "B":
                b += 1

    if both > 0:
        ans += both - 1

    if both > 0 and a > 0:
        ans += 1
        a -= 1

    if both > 0 and b > 0:
        ans += 1
        b -= 1

    ans += min(a, b)
    return ans

if __name__ == "__main__":
    N = int(input())
    Ss = [input() for _ in range(N)]
    print(solve(N, Ss))

Submission status: Accepted

Solution code:
n = int(input())
i = 0
b_top = 0
a_end = 0
ab_and = 0
ab_count = 0
while i < n:
  str = input()
  top_b = False
  if str[0] == 'B':
    b_top += 1
    top_b = True
  if str[-1] == 'A':
    a_end += 1
    if top_b:
      ab_and += 1
  ab_count += str.count('AB')
  i += 1

min_ab = min([b_top, a_end])
if b_top == a_end and b_top == ab_and and b_top > 0:
  min_ab -= 1
print(ab_count + min_ab)

Submission status: Accepted

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


def solve(N: int, s: "List[str]"):

    ABcount = 0
    Aend = 0
    Bstart = 0
    AendBstart = 0
    for i in range(N):
        ABcount += s[i].count("AB")
        if s[i][0] == "B" and s[i][-1] == "A":
            AendBstart += 1
        elif s[i][0] == "B":
            Bstart += 1
        elif s[i][-1] == "A":
            Aend += 1

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

    # 愚直
    # print("愚直")
    # ans = []
    # for kumi in itertools.permutations(s, N):
    #     ans.append("".join(kumi).count("AB"))
    # print(max(ans))
    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: Accepted

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


def solve(N: int, s: "List[str]"):

    ABcount = 0
    Aend = 0
    Bstart = 0
    AendBstart = 0
    for i in range(N):
        ABcount += s[i].count("AB")
        if s[i][0] == "B" and s[i][-1] == "A":
            AendBstart += 1
        elif s[i][0] == "B":
            Bstart += 1
        elif s[i][-1] == "A":
            Aend += 1

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

    # 愚直
    # print("愚直")
    # ans = []
    # for kumi in itertools.permutations(s, N):
    #     ans.append("".join(kumi).count("AB"))
    # print(max(ans))
    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: Accepted

Solution code:
def check(S):
    ans = 0
    for i in range(1,len(S)):
        if S[i-1] == 'A' and S[i] == 'B':
            ans += 1
    return ans

N = int(input())
s = []
a = 0
b = 0
ab = 0

ans = 0

for i in range(N):
    S = input()
    ans += check(S)
    if S[0] == 'B' or S[-1] == 'A':
        s.append(S)
        if S[0] == 'B' and S[-1] != 'A':
            b += 1
        elif S[0] != 'B' and S[-1] == 'A':
            a += 1
        else:
            ab += 1

if ab == 0:
    ans += min(a,b)
else:
    if a == 0 and b == 0:
        ans += ab - 1
    else:
        ans += ab + min(a,b)

print(ans)

Submission status: Accepted

Solution code:
N = int(input())

cnt = 0
cnt_BA = 0
cnt_A = 0
cnt_B = 0

for i in range(N) : 
    tmp = (input())
    cnt += tmp.count("AB")
    tmp = tmp[0] +tmp[-1]
    if tmp == "BA" : 
        cnt_BA += 1
    if tmp[-1] == "A" : 
        cnt_A += 1
    if tmp[0] == "B" : 
        cnt_B += 1
    
m = min(cnt_A, cnt_B)

if cnt_BA == cnt_A and cnt_BA == cnt_B and cnt_BA != 0 : 
    print(m-1+cnt)
else : 
    print(m+cnt)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def input_from_console():
    n = int(input())
    s_list = []
    for i in range(n):
        s_list.append(input())
    return n, s_list


def count_ab_in_string(s_list):
    return sum([item.count('AB') for item in s_list])


def count_start_with_b(s_list):
    return sum([1 if item.startswith('B') and not item.endswith('A') else 0 for item in s_list])


def count_end_with_a(s_list):
    return sum([1 if not item.startswith('B') and item.endswith('A') else 0 for item in s_list])


def count_end_with_a_and_start_with_b(s_list):
    return sum([1 if item.endswith('A') and item.startswith('B') else 0 for item in s_list])


def main():
    n, s_list = input_from_console()
    contains_count = count_ab_in_string(s_list)
    b = count_start_with_b(s_list)
    a = count_end_with_a(s_list)
    connect_count = min(b, a)  # ..a b...


    should_be_paired = count_end_with_a_and_start_with_b(s_list)
    # print(a, b, connect_count, should_be_paired)

    if should_be_paired > 0:
        if connect_count > 0:
            print(sum([contains_count, should_be_paired, 1, connect_count - 1]))
        elif a > 0 or b > 0:
            print(sum([contains_count, should_be_paired]))
        else:
            print(sum([contains_count, should_be_paired, -1]))
    else:
        print(sum([contains_count, connect_count]))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())

s = []

ans = 0

both = 0
a_a = 0
b_a = 0

for i in range(n):
	ss = input()
	ans += ss.count("AB")
	if(ss[0] == "B" and ss[len(ss)-1] == "A"):
		both += 1
	elif(ss[0] == "B"):
		b_a += 1
	elif(ss[len(ss)-1] == "A"):
		a_a += 1
		
if(both == 0):
	ans += min(a_a,b_a)
elif(a_a + b_a > 0):
	ans += (both + min(a_a,b_a))
elif(a_a + b_a == 0):
	ans += (both -1)

print(ans)

Submission status: Accepted

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


if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
N=int(input())
ans=A=B=BA=0
for _ in range(N):
    S=input()
    ans+=S.count("AB")
    if S[0]=='B'and S[-1]=='A':BA+=1
    elif S[0]=='B':B+=1
    elif S[-1]=='A':A+=1
if BA!=0:
    ans+= BA if A+B>0 else BA-1
print(ans+min(A,B))

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for i in range(N)]
#print(S)
a_cnt = 0
b_cnt = 0
ab_cnt = 0
b_a_cnt = 0
for i,s in enumerate(S):
    ab_cnt += s.count("AB")
    if s[-1] == "A":
        a_cnt += 1
    if s[0] == "B":
        b_cnt += 1
    if s[0] == "B" and s[-1] == "A":
        b_a_cnt += 1
if a_cnt == b_cnt == b_a_cnt and b_a_cnt != 0:
    ab_cnt += min(a_cnt, b_cnt) - 1
else:
    ab_cnt += min(a_cnt, b_cnt)

print(ab_cnt)

Submission status: Accepted

Solution code:
n,*t=open(0).read().split()
n=int(n)
a=0
b=0
c=0

ans=0
for i in t:
    if i[0]=="B"and i[-1]=="A":
        a+=1
    elif i[0]=="B":
        b+=1
    elif i[-1]=="A":
        c+=1
    ans+=i.count("AB")
if a>0 and b>0 and c>0:
    ans+=a+1
    a=0
    b-=1
    c-=1
if a>0 and b>0:
    ans+=a
    a=0
    b-=1
if a>0 and c>0:
    ans+=a
    a=0
    c-=1
if a>0:
    ans+=a-1
    a=0
if b>0 and c>0:
    ans+=min(b,c)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

a,b,c, = 0,0,0
ans = 0
for ll in l:
    for i in range(len(ll)-1):
        if ll[i:i+2] == 'AB':
            ans += 1
    if ll[-1] == 'A' and ll[0] != 'B':
        a += 1
    elif ll[-1] != 'A' and ll[0] == 'B':
        b += 1
    elif ll[-1] == 'A' and ll[0] == 'B':
        c += 1
if a == b == 0:
    print(max(ans+c-1,ans))
elif a == 0 or b == 0:
    print(ans+c)
else:
    print(ans + c+1 + min(a-1,b-1))

Submission status: Accepted

Solution code:
N = int(input())
res=0
first, end, both = 0, 0, 0


for i in range(N):
    str = input()
    res+=str.count("AB")
    if str[0]=="B":
        first+=1
    if str[-1]=="A":
        end+=1
    if str[0]=="B" and str[-1]=="A":
        both+=1

res+=min(first, end)
if both==max(first, end) and both!=0:
    res-=1

print(res)

Submission status: Accepted

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

end_A = 0
start_B = 0
sB_eA = 0
ans = 0

for s in S:
    ans += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        sB_eA += 1
    elif s[0] == 'B':
        start_B += 1
    elif s[-1] == 'A':
        end_A += 1

ans += min(start_B,end_A)

if start_B == 0 and end_A == 0:
    ans += max(0,sB_eA-1)
else:
    ans += sB_eA
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s_list = [input() for _ in range(n)]
res_ab = 0
res_ba = 0
res_a = 0
res_b = 0
for s in s_list:
    res_ab += s.count('AB')
    if s[0]=='B' and s[-1]=='A':
        res_ba += 1
    elif s[0]=='B':
        res_a += 1
    elif s[-1] == 'A':
        res_b += 1

if res_ba == 0:
    print(res_ab+min(res_a,res_b))
else:
    if res_a+res_b > 0:
        print(res_ab+res_ba+min(res_a,res_b))
    else:
        print(res_ab+res_ba-1)

Submission status: Accepted

Solution code:
N = int(input())

BA = 0
BX = 0
XA = 0

ans = 0

for i in range(N):
    S = input()
    if S[0] == 'B' and S[-1] == 'A':
        BA += 1
    elif S[0] == 'B':
        BX += 1
    elif S[-1] == 'A':
        XA += 1

    for a, b in zip(S, S[1:]):
        # print(a, b)
        if a == 'A' and b == 'B':
            ans += 1

# print(BA, BX, XA, ans)

if BA == 0:
    ans += min(BX, XA)
else:
    if BX == 0 and XA == 0:
        ans += BA - 1
    else:
        ans += BA + min(BX, XA)

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
s_list = []
count = 0
n, m, l = 0, 0, 0
 
for i in range(N):
  s = input()
  s_list.append(s)
  count += s.count('AB')
  if s[0] == 'B' and s[-1] == 'A':
    n += 1
    continue
  elif s[-1] == 'A':
    m += 1
  elif s[0] == 'B':
    l += 1

if m == 0 and l == 0:
  if n == 0:
    print(int(count))
  else:
    print(int(count + (n - 1)))
else:
  print(int(count + min(n+m, n+l)))

Submission status: Accepted

Solution code:
N = int(input())

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

ans = n_ab+min(n_b+n_both,n_a+n_both)
if n_both > 0 and n_a==0 and n_b==0:
    ans -= 1

print(int(ans))

Submission status: Accepted

Solution code:
n = int(input())
s = []
for i in range(n):
    s.append(input())
ans = 0
r = 0
l = 0
a = 0
b = 0
c = 0
for i in range(n):
    ans += s[i].count('AB')
    list = s[i]
    if list[-1] == 'A' and list[0] == 'B':
        r += 1
        l += 1
        c += 1
    elif list[-1] == 'A': # and list[0] != 'B':
        r += 1
        a += 1
    elif list[0] == 'B': # and list[-1] != 'A':
        l += 1
        b += 1
    # print(ans, last, start)
ans += min(r, l)
if a == 0 and b == 0 and c > 0:
    ans -= 1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
count, A, B, BA = 0, 0, 0, 0
for _ in range(N):
    s = input()
    count += s.count('AB')
    B += s[0] == 'B'
    A += s[-1] == 'A'
    BA += s[0] == 'B' and s[-1] == 'A'
    #print(s, A,B,BA, 'count', count)
tmp = (A - 1) if (A == B and A == BA and BA != 0) else min(A,B)
print(count + tmp)

Submission status: Accepted

Solution code:
N = int(input())
count, A, B, BA = 0, 0, 0, 0
for _ in range(N):
    s = input()
    count += s.count('AB')
    B += s[0] == 'B' and s[-1] != 'A'
    A += s[-1] == 'A' and s[0] != 'B'
    BA += s[0] == 'B' and s[-1] == 'A'
    #print(s, A,B,BA, 'count', count)

if BA == 0 :
    tmp = min(A,B)
else:
    if A + B > 0:
        tmp = BA + min(A,B)
    else:
        tmp = BA - 1
print(count + tmp)

Submission status: Accepted

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" and s[-1] != "A":
        B_start_cnt += 1
    if s[-1] == "A" and s[0] != "B":
        A_end_cnt += 1
    AB_cnt += s.count('AB')
ans = AB_cnt

if BA_cnt == 0:
    ans += min(A_end_cnt,B_start_cnt)
elif max(A_end_cnt,B_start_cnt)>0:
    ans += BA_cnt+min(A_end_cnt,B_start_cnt)
else:
    ans += BA_cnt-1
print(ans)

Submission status: Accepted

Solution code:
def sol(_inp=input):
    n=int(_inp())
    words=[_inp() for _ in range(n)]
    ab_in_words=sum(w.count('AB') for w in words)
    ends_A=sum(w.endswith('A') for w in words)
    starts_B=sum(w.startswith('B') for w in words)
    sands=sum((w.endswith('A') and w.startswith('B')) for w in words)
    if ends_A==sands and starts_B==sands and sands>0:
        return str(ab_in_words+sands-1)
    return str(ab_in_words+min(ends_A,starts_B))
print(sol())

Submission status: Accepted

Solution code:
N = int(input())

count_ab = 0
S_tail_a_head_b = 0
S_tail_a = 0
S_head_b = 0
for _ in range(N):
    s = input()
    count_ab += s.count('AB')

    if s[0] != 'B' and s[-1] != 'A':
        continue

    if s[0] == 'B' and s[-1] == 'A':
        S_tail_a_head_b += 1
    elif s[0] == 'B':
        S_head_b += 1
    elif s[-1] == 'A':
        S_tail_a += 1

if S_tail_a_head_b == 0:
    count_ab += min(S_tail_a, S_head_b)
else:
    count_ab += S_tail_a_head_b - 1
    if S_tail_a + S_head_b >= 1:
        count_ab += min(S_tail_a, S_head_b) + 1

print(count_ab)

Submission status: Accepted

Solution code:
import sys

def main():
    input = sys.stdin.readline
    N = int(input())
    ans = 0
    ba = 0  # Num. of str that the first letter is B and the last one is A.
    xa = 0  # Num. of str that the last letter is A and the first one is not B.
    bx = 0  # Num. of str that the first letter is B and the last one is not A.
    for _ in range(N):
        s = str(input().strip())

        # Count the number of AB contained in the initial strings.
        for i in range(len(s)):
            if s[i:i+2] == 'AB':
                ans += 1

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

    if ba == 0:
        # One xa ans one bx make one new "AB".
        #   xa + bx -> xABx
        ans += min(xa, bx)

    elif max(xa, bx) == 0:
        # N of ba make N-1 new "AB".
        # BxxA + BxxA + ... + BxxA -> BxxABxxAB...ABxxA
        ans += ba - 1

    else:  # There is at least one bx or ax and at least one ba.
        # N of ba make N-1 new "AB" and a ba.
        #   ba + ba + ... + ba -> baba...ba = ba
        # The last remaining ba and bx/ax make a new "AB" and a new bx/ax.
        #   ba + bx -> bABx = bx,  xa + ba -> xABa = xa
        # Then, bx and xa make a new "AB".
        #   xa + bx -> xABx 
        ans += ba + min(xa, bx)

    return ans


if __name__ == '__main__':
    print(main())

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from sys import stdin
N=int(stdin.readline().rstrip())
 
data=[]
ans=0
A=0
B=0
ab=0
for i in range(N):
    S=input()
    ans+=S.count("AB")
    if S[0] == "B":
        B+=1
    if S[-1] == "A":
        A+=1
    if S[-1] == "A" and S[0] == "B":
        ab+=1
if ab == 0:
    print(ans+min(A,B))
    
elif A == B == ab:
    print(ans+ab-1)

else:
    print(ans+min(A,B))

Submission status: Accepted

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

cnt_ab_from_S = sum([s.count('AB') for s in S])
start_from_b_and_end_at_a = sum([(s[0] == 'B') and (s[-1] == 'A') for s in S])
not_start_from_b_and_end_at_a = sum([(s[0] != 'B') and (s[-1] == 'A') for s in S])
start_from_b_and_not_end_at_a = sum([(s[0] == 'B') and (s[-1] != 'A') for s in S])

ans = cnt_ab_from_S
if (start_from_b_and_end_at_a == 0):
    ans += min(not_start_from_b_and_end_at_a, start_from_b_and_not_end_at_a)
elif (not_start_from_b_and_end_at_a + start_from_b_and_not_end_at_a == 0):
    ans += (start_from_b_and_end_at_a - 1)
else:
    ans += (start_from_b_and_end_at_a + min(not_start_from_b_and_end_at_a, start_from_b_and_not_end_at_a))
print(ans)

Submission status: Accepted

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


def solve(N: int, s: "List[str]"):
    x = 0; a = 0; b = 0
    ans2 = 0
    for i in s:
        ans2 += i.count('AB')
        if(i[0] == 'B' and i[-1] == 'A'):
            x += 1
        elif(i[-1] == 'A'):
            a += 1
        elif(i[0] == 'B'):
            b += 1
    
    #####    AC2   ####
    ans1 = max(0,x-1) + min(a,b)
    if((a > 0 or b >0) and x > 0):
        ans1 += 1
    
    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: Accepted

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


def solve(N: int, s: "List[str]"):
    x = 0
    a = 0
    b = 0
    ans2 = 0
    for i in s:
        ans2 += i.count('AB')
        if(i[0] == 'B' and i[-1] == 'A'):
            x += 1
        elif(i[-1] == 'A'):
            a += 1
        elif(i[0] == 'B'):
            b += 1
    
    
    ####   AC1   #####    
    # if(x == 0):
    #     ans1 = min(a,b)
    # else:
    #     ans1 = max(0,x-1)+min(a,b)
    #     if(a > 0 or b > 0):
    #         ans1 += 1
    
    #####    AC2   ####
    ans1 = max(0,x-1) + min(a,b)
    if((a > 0 or b >0) and x > 0):
        ans1 += 1
    
    ####   WA    #############
    # ans1 = max(0,x-1) + min(a,b)
    # if(x != 0):
    #     ans1 += 1 
    

    # ans1 = max(0,x-1) 
    # if(a == b):
    #     ans1 += min(a,b)
    #     if((a > 0 or b > 0) and x != 0):
    #         ans1 += 1
    # else:
    #     if(x == 0):
    #         ans1 += min(a,b)
    #     elif(a > 0 or b > 0):
    #         ans1 += 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: Accepted

Solution code:
import sys

input = sys.stdin.readline
n = int(input())
s_list = []
xa_num = 0
bx_num = 0
ba_num = 0
cnt = 0
for _ in range(n):
    s_in = input()[:-1]
    if s_in[0] == 'B':
        if s_in[-1] == 'A':
            ba_num += 1
        else:
            bx_num += 1
    elif s_in[-1] == 'A':
        xa_num += 1
    flag = 0
    for s in s_in:
        if s == 'A':
            flag = 1
        elif s == 'B':
            if flag == 1:
                cnt += 1
            flag = 0
        else:
            flag = 0

if ba_num == 0:
    print(cnt+min(xa_num, bx_num))
elif xa_num + bx_num == 0:
    print(cnt+ba_num-1)
else:
    print(cnt+ba_num+min(xa_num, bx_num))

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
c1, c2, c3 = 0, 0, 0
for i in range(n):
    s = input()
    ans += s.count('AB')
    l = len(s)
    if (s[0] == 'B') & (s[l - 1] == 'A'):
        c3 += 1
    elif s[0] == 'B':
        c1 += 1
    elif s[l - 1] == 'A':
        c2 += 1
if (c1 == 0) & (c2 == 0):
    ans += max(0, c3 - 1)
else:
    ans += min(c1, c2) + c3
print(ans)

Submission status: Accepted

Solution code:
# from time import perf_counter


def main():
    n = int(input())
    words = []
    for _ in range(n):
        words.append(input())

    categorized = []
    for word in words:
        idt = len(categorized)
        itself = word.count('AB')

        has_A_rs = word.endswith('A')
        # has_B_rs = word.endsWith('B')
        # has_A_ls = word.startsWith('A')
        has_B_ls = word.startswith('B')

        categorized.append({
            'w': word, '#': idt, 'itself': itself,
            'rA': has_A_rs, 'lB': has_B_ls
        })

    # lXrX = [w for w in categorized if not w['rA'] and not w['rB']]
    lBrA = len([w for w in categorized if w['rA'] and w['lB']])
    lBrX = len([w for w in categorized if not w['rA'] and w['lB']])
    lXrA = len([w for w in categorized if w['rA'] and not w['lB']])

    s = sum([w['itself'] for w in categorized])
    if lBrA == 0:
        s += min(lBrX, lXrA)
    elif lBrX + lXrA > 0:
        s += lBrA + min(lBrX, lXrA)
    else:
        s += lBrA - 1

    print(s)


if __name__ == '__main__':
    # s = perf_counter()
    main()
    # e = perf_counter()
    # print('process:', e - s)

Submission status: Accepted

Solution code:
n = int(input())
S = [input() for _ in range(n)]
ab = 0
ba = 0
bx = 0
xa = 0
for s in S:
    if s[0] == 'B' and s[-1] == 'A':
        ba += 1
    elif s[0] == 'B' and s[-1] != 'A':
        bx += 1
    elif s[0] != 'B' and s[-1] == 'A':
        xa += 1
    for i in range(len(s) - 1):
        if s[i] == 'A' and s[i + 1] == 'B':
            ab += 1
if ba > 1:
    ab += ba - 1
    ba = 1
ab += min(xa, bx)
xa -= min(xa, bx)
bx -= min(xa, bx)
if ba == 1 and xa != bx:
    ab += 1
print(ab)