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:
from collections import Counter
from collections import deque
from functools import reduce
from pprint import pprint
# import statistics
import bisect
import copy
import fractions
import math
import random
import sys
import time
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def MI(): return map(int, sys.stdin.readline().split())
def II(): return int(sys.stdin.readline())
def IS(): return input()
def C(x): return Counter(x)
def GCD_LIST(numbers):
    return reduce(fractions.gcd, numbers)
def LCM_LIST(numbers):
    return reduce(LCM, numbers)
def LCM(m, n):
    return (m * n // fractions.gcd(m, n))
def unite(x, y):
    # それぞれのノードの根を求める
    x = root(x)
    y = root(y)
    if x == y:
        return
    # node[x]の根をyに変更する
    node[x] = y
def same(x,y): return bool(root(x) == root(y))
def root(x):
    if node[x] == x:  # xが根の場合
        return x
    else:
        node[x] = root(node[x])  # 経路圧縮
        return node[x]
def dfs(v):
    # ノードに訪れた
    visited[v] = True
    for v2 in range(n):
        if graph[v][v2] == False:  # そもそもvとv2が辺でつながっていない
            continue
        if visited[v2] == True:  # もう見た
            continue
        dfs(v2)

n = II()
s = [IS() for _ in range(n)]
cnt = 0
sentou_b = 0
ushiro_a = 0
ab = 0
for i in s:
    cnt += i.count('AB')
    if i[0] == 'B' and i[-1] == 'A':
        ab += 1
    else:
        if i[0] == 'B':
            sentou_b += 1
        if i[-1] == 'A':
            ushiro_a += 1
if ab == 0:
    print(cnt+min(sentou_b, ushiro_a))
elif ab > 0:
    if sentou_b + ushiro_a > 0:
        print(cnt+ab+min(sentou_b, ushiro_a))
    elif sentou_b + ushiro_a == 0:
        print(cnt+ab-1)

Submission status: Accepted

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

Bset = set()
Aset = set()
ans = 0
for i in range(n):
    if s[i][0] == "B":
        Bset.add(i)
    if s[i][-1] == "A":
        Aset.add(i)
    for j in range(1, len(s[i])):
        if s[i][j - 1] == "A" and s[i][j] == "B":
            ans += 1

Bli = list(Bset)
Ali = list(Aset)
ans += min(len(Bli), len(Ali))
if Bset == Aset and Bset != set():
    ans -= 1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())

cnt = 0
b_start = 0
a_end = 0
b_start_and_a_end = 0

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

cnt += min(a_end,b_start)

if b_start == a_end == 0:
    cnt += max(0,b_start_and_a_end-1)
else:
    cnt += b_start_and_a_end

print(cnt)

Submission status: Accepted

Solution code:
N = int(input())
headB=0
tailA=0 
both = 0
ans = 0
for j in range(N):
    t = input()
    if t[0] == "B":
        if t[-1] == "A":
            both += 1
        else:
            headB += 1
    elif t[-1] == "A":
        tailA += 1
    ans += t.count("AB")
if both > 0:
    ans += both - 1
    if tailA > 0 or headB > 0:
        ans += 1
ans += min(tailA,headB)
print(ans)

Submission status: Accepted

Solution code:
import re
aflag = 0
bflag = 0
cnt = 0
cntna = 0

N = int(input())
for i in range(N):
    s = input()
    if s[-1:] == "A":
        aflag += 1
    if s[:1] == "B":
        bflag += 1
    if re.search("AB", s):
        cnt += 1
    if re.search("AB.*AB", s):
        cnt += 1
    if re.search("AB.*AB.*AB", s):
        cnt += 1
    if re.search("AB.*AB.*AB.*AB", s):
        cnt += 1
    if re.search("ABABABABAB", s):
        cnt += 1
    if s[-1:]=="A" and s[:1]=="B":
        cntna +=1

cnt += min(aflag, bflag)
if min(aflag,bflag) == N:
    cnt -= 1
if cntna == min(aflag, bflag) and aflag == bflag and aflag != 0 and bflag != 0:
    cnt -= 1
if aflag == bflag == N:
    cnt += 1
print(cnt)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1000000)

def f(a,b,ba):
  if a>0 and ba>0:
    return 1 + f(a,b,ba-1)
  elif a>0 and b>0:
    return 1+ f(a-1,b-1,ba)
  elif ba>1:
    return 1 + f(a+1,b,ba-2)
  elif ba>0 and b>0:
    return 1 + f(a,b-1,ba-1)

  return 0

N=int(input())
a=[]
b=[]

stA=0
stB=0
stBA=0

ans=0
for x in range(N):
  z=input()
  buf=z.count("AB")
  b.append((z[0],z[-1],buf))
  ans+=buf

for z in b:
  if z[0]=="B" and z[1]=="A":
    stBA+=1
  elif z[0]=="B":
    stB+=1
  elif z[1]=="A":
    stA+=1

ans=ans+f(stA,stB,stBA)
print(ans)

Submission status: Accepted

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

    for j in range(len(a[i])):
        # print(a[i][j])
        if a[i][j] == "B" and flag:
            cnt += 1
        flag = False

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

print(
    cnt + min(tBeNA, tNBeA) if tBeA == 0 else cnt + min(tBeNA, tNBeA) + tBeA if tNBeA + tBeNA > 0 else cnt + min(tBeNA,
                                                                                                                 tNBeA) + tBeA - 1)

Submission status: Accepted

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


def main():
    n = int(input())
    s = [input() for _ in range(n)]
    ans = 0
    back_a_count = 0
    front_b_count = 0
    front_b_back_a_count = 0

    for si in s:
        if si[0] == 'B':
            front_b_count += 1
        if si[-1] == 'A':
            back_a_count += 1
        if si[0] == 'B' and si[-1] == 'A':
            front_b_back_a_count += 1

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

    ans += min(back_a_count, front_b_count)

    # See:
    # https://www.youtube.com/watch?v=AQOZYEk54rw
    if front_b_count == back_a_count == front_b_back_a_count:
        if front_b_back_a_count > 0:
            ans -= 1

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def c(strs):
    count = 0
    count_a = 0
    count_b = 0
    flag = 1
    for s in strs:
        count += s.count('AB')
        if s[0]=='B' and s[-1]=='A':
            count_a += 1
            count_b += 1
        elif s[0]=='B':
            count_b += 1
            flag = 0
        elif s[-1]=='A':
            count_a += 1
            flag = 0
    if count_a:
        return count + min(count_a,count_b) - flag
    return count


if __name__=='__main__':
    n = int(input())
    s = []
    for _ in range(n):
        s.append(input())
    print(c(s))

Submission status: Accepted

Solution code:
def c_ab_substrings(N, S):
    """
    N個の文字列を好きな順序で並べたあと、連結して1つの文字列を作る。
    作った文字列に 'AB' という部分文字列が含まれる個数として
    ありうる値のうち最大のものを求めよ。
    """

    num_start_b_end_a = 0
    num_start_b_not_end_a = 0
    num_not_start_b_end_a = 0
    ans = 0
    for s in S:
        if s[0] == 'B' and s[-1] == 'A':
            num_start_b_end_a += 1
        if s[0] == 'B' and s[-1] != 'A':
            num_start_b_not_end_a += 1
        if s[0] != 'B' and s[-1] == 'A':
            num_not_start_b_end_a += 1
        ans += s.count('AB')
    if num_start_b_end_a == 0:
        # 'B.*A' がない場合、'B.*^A' と '^B.*A' を結合して '.*AB.*' を生み出せる
        ans += min(num_start_b_not_end_a, num_not_start_b_end_a)
    else:
        # 'B.*A' がある場合、その後に 'B.*^A' を結合するか、その前に '^B.*A' を結合する
        # 'B.*^A' も '^B.*A' もない場合、 'B.*A' 同士で結合させる
        if num_start_b_not_end_a + num_not_start_b_end_a > 0:
            ans += num_start_b_end_a + min(num_start_b_not_end_a, num_not_start_b_end_a)
        else:
            ans += num_start_b_end_a - 1
    return ans

N = int(input())
S = [input() for _ in range(N)]
print(c_ab_substrings(N, S))

Submission status: Accepted

Solution code:
headB = 0
tailA = 0
both = 0
c = 0
for i in range(int(input())):
    t = input()
    if t[0] =='B' and t[-1]=='A':
        both+=1
    elif t[0] == 'B':
        headB+=1
    elif t[-1] == 'A':
        tailA +=1
    c+=t.count('AB')
if both>0:
    if tailA+headB>0:
        if tailA:
            c+=1
            tailA-=1
        if headB:
            c+=1
            headB-=1
        c+=min(headB,tailA)
        c+=both-1
    else:
        c+=both-1
else:
    c+=min(tailA,headB)
print(c)

Submission status: Accepted

Solution code:
n = int(input())
S = []
result = 0
A_count = 0
B_count = 0
BA_count = 0

for i in range(n):
    Si = str(input())
    S.append(Si)

for i in range(n):
    Si = S[i]
    result += Si.count("AB")
    if Si[0] == "B" and Si[-1] != "A":
        B_count += 1
    if Si[0] != "B" and Si[-1] == "A":
        A_count += 1
    if Si[0] == "B" and Si[-1] == "A":
        BA_count += 1 

if BA_count >= 2:
    result += (BA_count - 1)

if BA_count >= 1:
    if B_count >= 1:
        result += 1
        B_count -= 1
    if A_count >= 1:
        result += 1
        A_count -= 1

if B_count >= 1 and A_count >= 1:
    result += min(B_count, A_count)

print(result)

Submission status: Accepted

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

contained = sum([s.count('AB') for s in ss])
B_hoge = sum([1 for s in ss if s[0]=='B'])
hoge_A = sum([1 for s in ss if s[-1]=='A'])
B_hoge_A = sum([1 for s in ss if s[0]=='B' and s[-1]=='A'])

B_hoge -= B_hoge_A
hoge_A -= B_hoge_A

ans = contained
if B_hoge_A==0:
    ans += min(B_hoge, hoge_A)
elif B_hoge + hoge_A > 0:
    ans += B_hoge_A + min(B_hoge, hoge_A)
else:
    ans += B_hoge_A -1
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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


if a_and_b == 0:
    print(count + min(end_a, start_b))
elif end_a + start_b == 0:
    print(count + a_and_b - 1)
else:
    print(count + a_and_b + min(end_a, start_b))

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline

N = int(input())
A, B, AB = 'A', 'B', 'AB'
endA, startB, startB_endA = 0, 0, 0
ans = 0

for _ in range(N):
    S = input().rstrip()

    if S[0] == B:
        startB += 1

        if S[-1] == A:
            startB -= 1
            startB_endA += 1

    elif S[-1] == A:
        endA += 1
    

    for i in range(1,len(S)):
        if S[i-1] + S[i] == AB:
            ans += 1


if startB_endA == 0:
    ans += min(endA, startB)

elif endA == 0 and startB == 0:
    ans += max(0, startB_endA - 1)

else:
    ans += startB_endA + min(endA, startB)

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
 
g1 = []
g2 = []
g3 = []
 
cnt = 0
 
for i in range(n):
    s = input()
    cnt += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        g3.append(s)
    elif s[0] == "B":
        g1.append(s)
    elif s[-1] == "A":
        g2.append(s)
        
a = len(g1)
b = len(g2)
c = len(g3)
 
if a == b:
    if a == c:
        cnt += c * 2
    elif a > c:
        cnt += c
        cnt += a
    elif a < c:
        if a == 0:
            cnt += c - 1
        else:
            cnt += a
            cnt += c
elif a > b:
    cnt += b
    cnt += c
elif b > a:
    cnt += a
    cnt += c
 
print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
s = []

b = 0
a = 0
ba = 0
ans = 0

for i in range(n):
    s.append(input())
    ans += s[i].count('AB')
    if s[i].startswith('B') and s[i].endswith('A'):
        ba += 1
    elif s[i].startswith('B'):
        b += 1
    elif s[i].endswith('A'):
        a += 1

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

print(ans)

Submission status: Accepted

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

a, b, ba, ab = 0, 0, 0, 0
for ss in s:
    ab += ss.count('AB')

    bl_a = ss[-1] == 'A'
    bl_b = ss[0] == 'B'
    if bl_a:
        if bl_b:
            ba += 1
        else:
            a += 1
    else:
        if bl_b:
            b += 1
        else:
            pass

ans = 0
ans += ab

if ba > 0:
    # ba > 0
    ans += ba - 1
    if a > 0:
        ans += 1
        a -= 1
    if b > 0:
        ans += 1
        b -= 1

ans += min(a, b)
print(ans)

"""
...AB...
ab

B...A
ba

...A
a

B...
b
"""

Submission status: Accepted

Solution code:
N = int(input())
s = [input() for i in range(N)]
flg = 1
cnt = 0
ca = 0
cb = 0
for i in range(N):
  if s[i][0] == 'B' and s[i][-1] == 'A':
    ca += 1
    cb += 1
  elif s[i][0] == 'B':
    cb += 1
    flg = 0
  elif s[i][-1] == 'A':
    ca += 1
    flg = 0
  cnt += s[i].count('AB')

if  min(ca, cb) > 0:
  cnt += min(ca, cb) - flg

print (cnt)

Submission status: Accepted

Solution code:
N = int(input())
S=[]
ans=0
ab=0
a=0
b=0
for i in range(N):
    tmp=input()
    ans+=tmp.count("AB")
    if tmp[-1]=="A" and tmp[0]=="B":
        ab +=1
    elif tmp[-1]=="A":
        a+=1
    elif tmp[0]=="B":
        b+=1
    S.append(tmp)
#print(ans,ab,a,b)
if(ab==0):
    print(ans+min(a,b))
elif(a==0 and b==0):
    print(ans+ab-1)
else:
    print(ans+ab+min(a,b))

Submission status: Accepted

Solution code:
n = int(input())
s_array = [input() for x in range(n)]
last_a = 0
reversible = 0
start_b = 0
flag = False
for s in s_array:
    if s[-1] == "A" and s[0] != "B":
        last_a += 1
    elif s[0] == "B" and s[-1] != "A":
        start_b += 1
    elif s[0] == "B" and s[-1] == "A":
        reversible += 1
    else:
        flag = True
res = 0
for s in s_array:
    res += s.count("AB")

if start_b > last_a or flag:
    tmp = 0
else:
    tmp = 1

if n == 1:
    print(res)
elif reversible == 0:
    print(res + min(last_a, start_b))
elif last_a == 0 and start_b == 0:
    print(res + reversible - 1)
elif last_a == 0 or start_b == 0:
    print(res + min(last_a, start_b) + reversible)
else:
    print(res + min(last_a, start_b) + reversible)

# a = []
# b = []
# other = []
# for s in s_array:
#     if s[0] == "B":
#         b.append(s)
#     elif s[-1] == "A":
#         a.append(s)
#     else:
#         other.append(s)
# res = ""
# print(a, b, other)
# for i in a:
#     res += i
#     for j in b:
#         res += j
#         continue
# for i in other:
#     res += i
# a_flag = False
# cnt = 0
# print(res)
# for i in res:
#     if i == "B" and a_flag:
#         cnt += 1
#     if i == "A":
#         a_flag = True
#     else:
#         a_flag = False
# print(cnt)

Submission status: Accepted

Solution code:
#b_a,x_a,b_xそれぞれの数を取得し、b_aがあればb_aだけの連結で(b_a)-1個のABが作られる。かつx_a,b_xがあれば両端にABを作ることができる。
#その分x_a.b_xのみで使う予定のものが一つずつ減る。

N = int(input())
S = [input() for i in range(N)]
ab = x_a = b_x = b_a = 0
for s in S:
    ab += s.count('AB')
    if s[-1]=='A' and s[0]=='B':
        b_a += 1
    elif s[-1]=='A':
        x_a += 1
    elif s[0]=='B':
        b_x += 1
        
ans = ab

#b_aが一つでもあれば
if b_a:
    #b_aだけで繋げた時のABの数を追加
    ans += b_a - 1
    if x_a:
        #b_aの左端にx_aをつなげることでできるAB
        ans += 1
        #その代わりにx_aとb_xで使う用のx_aが一つ減る
        x_a -= 1
    if b_x:
        ans += 1
        b_x -= 1
        
#最後に残ったx_aとb_xで作られるABの数を追加する
ans += min(x_a, b_x)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = [input() for i in range(n)]
count = 0
count_a = 0
count_b = 0
count_ab = 0
for i in range(n):
    count += s[i].count("AB")
    if s[i][-1] == "A" and s[i][0] != "B":
        count_a += 1
    if s[i][0] == "B" and s[i][-1] != "A":
        count_b += 1
    if s[i][0] == "B" and s[i][-1] == "A":
        count_ab += 1


if count_ab == 0:
    print(count+min([count_a,count_b]))
else:
    if count_a + count_b == 0:
        print(count+count_ab-1)
    else:
        print(count+min([count_a,count_b])+count_ab)

Submission status: Accepted

Solution code:
import re

N = int(input())

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

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


if BtoA == 0:
    ans = AB + min(startB, stopA)
elif startB + stopA > 0:
    ans = AB + min(startB, stopA) + BtoA
else:
    ans = AB + min(startB, stopA) + BtoA - 1
print(ans)

Submission status: Accepted

Solution code:
import sys 
import re

input()
bsn = 0
aen = 0
cen = 0
t = 0
for line in sys.stdin:
    st = line.strip()
    t += st.count("AB")
    if st[0] == "B" and st[-1] == "A":
        cen += 1
    elif st[0] == "B":
        bsn += 1
    elif st[-1] == "A":
        aen += 1

if aen != 0:
    if bsn != 0:
        if cen != 0:
            x = min(bsn-1, aen-1)
            print(t+cen+1+x)
        else:
            x = min(bsn, aen)
            print(t+x)
    else:
        print(t+cen)
else:
    if bsn != 0:
        print(t+cen)
    else:
        if cen != 0:
            print(t+cen-1)
        else:
            print(t)

Submission status: Accepted

Solution code:
N = int(input())

count = 0
ba = 0
b = 0
a = 0

for _ in range(N):
    s = input()
    if s[0] == "B":
        if s[-1] == "A":
            ba += 1
        else:
            b += 1
    elif s[-1] == "A":
        a += 1

    n = len(s)
    for i in range(n-1):
        if s[i] == "A" and s[i+1] == "B":
            count += 1

# BA
count += max(ba-1, 0)

if ba >= 1:
    if a >= 1 and b >= 1:
        count += 2
        a -= 1
        b -= 1
    elif a > b:
        count += 1
        a -= 1
    elif b > a:
        count += 1
        b -= 1

#if a >= 1 and b >= 1:
count += min(a, b)        

print(count)

Submission status: Accepted

Solution code:
#! usr/bin/env python
# -*- coding: utf-8 -*-

from collections import deque
import heapq
import math
import bisect


def main():
    N = int(input())
    S = [input() for i in range(N)]

    a = b = ab = 0
    ans = 0
    for s in S:
        n = len(s)
        for j in range(n-1):
            if s[j] == "A" and s[j+1] == "B":
                ans += 1
        if s[0] == "B" and s[-1] == "A":
            ab += 1
        elif s[0] == "B":
            b += 1
        elif s[-1] == "A":
            a += 1

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


if __name__ == '__main__':
    main()

Submission status: Accepted

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

target = "AB"
for i in range(N):
	index = -1
	while True:
		index = s[i].find(target, index + 1)
		if index == -1:
			break
		count += 1


# これだけだと1文中に2文以上あるときに検出できない
# for i in range(N):
# 	index = s[i].find("AB")
# 	if index != -1:
# 		count += 1
a=0
b=0
ba=0


for i in range(N):
	if s[i][-1]=="A" and s[i][0]=="B":
		ba+=1
	elif s[i][-1] == "A" and s[i][0] != "B":
		a+=1
	elif s[i][-1] != "A" and s[i][0] == "B":
		b+=1
# print("a",a)
# print(b)
# print(ba)
"""
one=min(a,b)
two=0
if ba>0:
	two=ba-1

	if abs(a-b)>0:
		two=ba-1+1
print(one+two+count)
"""

if ba==0:
	count+=min(a,b)
else:
	if a==0 and b==0:
		count += (ba - 1)
	elif a == 0 or b == 0:
		count += ba
	else:
		count +=(ba + min(a,b))
		# min(a, b) : -A,B-同士が結合する数
		# B-AはB-A同士で結合する 数：ba-1
		# 結合したB-Aの最初はB，最後はAになっているので，
		# そのどちらかに-A,B-が結合したものがくっつくき，また結合が1つできる 数：ba-1+1 = ba
# if a >= 1 and b >= 1:
# 	count += ba + min(a, b)
# elif a >= 1 or b >= 1:
# 	count += ba
# else:
# 	count += max(0, ba - 1)

print(count)

Submission status: Accepted

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

# 'AB'の数を数える
cnt_ab = sum([s.count('AB') for s in S])

# L: 先頭が'B'、終わりが'A'の数を数える
cnt_b_a = sum([(s[0] == 'B') and (s[-1] == 'A') for s in S])

# M: 先頭が'B'、終わりが'A'じゃないの数を数える
cnt_b_na = sum([(s[0] == 'B') and (s[-1] != 'A') for s in S])

# N : 先頭が'B'じゃなく、終わりが'A'の数を数える
cnt_nb_a = sum([(s[0] != 'B') and (s[-1] == 'A') for s in S])

count = cnt_ab
if (cnt_b_a == 0): # MとNの数の小さい方の分だけ追加できる
    count += min(cnt_b_na, cnt_nb_a)
elif (cnt_b_na + cnt_nb_a == 0): # Lの個数 - 1個だけ追加できる
    count += (cnt_b_a - 1)
else:
    count += (cnt_b_a + min(cnt_b_na, cnt_nb_a))
print(count)

Submission status: Accepted

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

# 先頭がBである／ではない、末尾がAである／ではない文字列の個数を数え上げる
a = sum(t[0] != 'B' and t[-1] == 'A' for t in s)
b = sum(t[0] == 'B' and t[-1] != 'A' for t in s)
ba = sum(t[0] == 'B' and t[-1] == 'A' for t in s)

# 最初に、先頭文字がBではない、かつ、末尾文字がAの文字列を先頭におく（そのような文字列が存在すれば）
# 次に、先頭文字がB、かつ、末尾文字がAの文字列を可能な限り連結する
# 次に、（先頭文字がB、かつ、末尾文字がAでない文字列）と（先頭文字がBではない、かつ、末尾文字がAの文字列）を交互に連結する
# 最後に、余っている文字列を適当に連結する
ans = (
    sum(t.count('AB') for t in s) +
    (
        ba if a > 0 else
        max(0, ba - 1)
    ) +
    (
        min(1, b) if a == 0 and ba > 0 else
        min(a, b)
    )
)

# 出力
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
s=['' for i in range(n)]
for i in range(n):
  s[i]=input()
#print(n,s)
cnt=0
cnta=0
cntb=0
cntab=0
ans=0
for i in range(n):
    cnt+=s[i].count('AB')
    if s[i][-1]=='A' and s[i][0]=='B':
        cntab+=1
    elif s[i][-1]=='A':
        cnta+=1
    elif s[i][0]=='B':
        cntb+=1

if cntab==0:
  ans=cnt+min(cnta,cntb)
else:
  ans=cnt+cntab+min(cnta,cntb)

if cnta==0 and cntb==0:
  if cntab > 0:
    ans=cnt+cntab-1
  else:
    ans=cnt
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
ans = 0
pattern = {"BA":0,"A":0,"B":0}
for i in range(N):
    s = input()
    ans += s.count("AB")
    if(s[0]=="B" and s[-1]=="A"):
        pattern["BA"]+=1
    elif(s[-1]=="A"):
        pattern["A"]+=1
    elif(s[0]=="B"):
        pattern["B"]+=1

if pattern["BA"]==0:
    ans += min(pattern["A"], pattern["B"])
else:
    ans += pattern["BA"]-1
    ans += pattern["A"]>0
    ans += pattern["B"]>0
    ans += max(0, min(pattern["A"]-1, pattern["B"]-1))
print(ans)

Submission status: Accepted

Solution code:
N = int(input())

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

ab_cnt = 0
a_cnt = 0
b_cnt = 0
in_cnt = 0

for tmp_list in ab_list:
    # Count 'AB'
    in_cnt += tmp_list.count('AB')
    
    # Conut start'B' and end 'A'
    if tmp_list.startswith('B') and tmp_list.endswith('A'):
        ab_cnt += 1
        
    # Count end'A'
    elif tmp_list.endswith('A'):
        a_cnt += 1
    
    # Count start'B'
    elif tmp_list.startswith('B'):
        b_cnt += 1
        
# compute count of 'AB'
if ab_cnt == 0:
    ans = min(a_cnt, b_cnt) + in_cnt
elif a_cnt + b_cnt > 0:
    ans = ab_cnt + min(a_cnt, b_cnt) + in_cnt
elif a_cnt + b_cnt == 0:
    ans = (ab_cnt -1) + in_cnt

# output
print(ans)

Submission status: Accepted

Solution code:
import re
N = int(input())
s = [input() for i in range(N)]

count_AB = 0
count_A = set()
count_B = set()

for i in range(N):
    _s = s[i]
    if _s[0] == "B":
        count_B.add(i)
    if _s[len(_s)-1] == "A":
        count_A.add(i)
    count_AB += len(re.findall("AB", _s))


inter = (count_A & count_B)
count_max = max(len(count_A), len(count_B))
count_min = min(len(count_A), len(count_B))
cnt = 0
if len(inter) == 0:
    cnt = count_min
elif len(inter) == count_max:
    cnt = len(inter) - 1
else:
    cnt = count_min


print(count_AB + cnt)

Submission status: Accepted

Solution code:
from sys import stdin
n = int(stdin.readline().rstrip())
ans=0
ba=0
bx=0
xa=0
for i in range(n):
  s = stdin.readline().rstrip()
  for j in range(len(s)-1):
    if s[j] == 'A' and s[j+1] == 'B':
      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(xa,bx)
if ba>0:
  ans += (ba-1)
  if (xa+bx)!=0:
    ans += 1

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for _ in range(N)]
ans = 0
ba = b = a = 0
for s in S:
    ans += s.count('AB')
    if s[0] + s[-1] == 'BA':
        ba += 1
    elif s[0] == 'B':
        b += 1
    elif s[-1] == 'A':
        a += 1
if ba == 0:
    ans += min([b, a])
elif b or a:
    ans += ba + min([b, a])
else:
    ans += ba + min([b, a]) - 1
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n=int(input())
S=[list(input())for i in range(n)]
A_cnt=0
B_cnt=0
AB_cnt=0
for s in S:
        if s[0]=="B" and s[-1]=="A":
                AB_cnt+=1
        elif s[-1]=="A":
                A_cnt+=1
        elif s[0]=="B":
                B_cnt+=1
cnt=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":
                        cnt+=1
if A_cnt==B_cnt==0 and 0<AB_cnt:
        print(AB_cnt-1+cnt)
else:
        print(cnt+min(A_cnt+AB_cnt,B_cnt+AB_cnt))

Submission status: Accepted

Solution code:
n=int(input())
S=[list(input())for i in range(n)]
A_cnt=0
B_cnt=0
AB_cnt=0
for s in S:
        if s[0]=="B" and s[-1]=="A":
                AB_cnt+=1
        elif s[-1]=="A":
                A_cnt+=1
        elif s[0]=="B":
                B_cnt+=1

cnt=0
for i in range(n):
        S[i].append("T")
        for j in range(len(S[i])):
                if S[i][j]=="A" and S[i][j+1]=="B":
                        cnt+=1
if A_cnt==B_cnt==0 and 0<AB_cnt:
        print(AB_cnt-1+cnt)
else:
        print(cnt+min(A_cnt+AB_cnt,B_cnt+AB_cnt))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun May 12 12:43:59 2019

@author: Yamazaki Kenichi
"""

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

ans = 0
firstB, lastA, u = 0, 0, 0
for s in S:
    flg = False
    for c in s:
        if flg and c == "B":
            ans += 1
        flg = False
        if c == 'A':
            flg = True
    if s[0] == 'B':
        firstB += 1
    if s[-1] == 'A':
        lastA += 1
    if s[0] == 'B' and s[-1] == 'A':
        u += 1
ans += min(firstB,lastA)
ans -= 1 if u == firstB and u == lastA and u != 0 else 0
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
topb = 0
taila = 0
both = 0
cnt = 0
for _ in range(N):
    s = input()
    cnt +=s.count("AB")

    if s[0] == "B" and s[-1] == "A":
        both += 1
    elif s[0] == "B":
        topb += 1
    elif s[-1] == "A":
        taila += 1
add_cnt = 0
if taila == 0 and topb == 0 and both >0:
    add_cnt = both -1
else:
    add_cnt = min(taila + both,topb + both)

print(cnt + add_cnt)

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for _ in range(N)]
ans = 0
ba = b = a = 0
for s in S:
    ans += s.count('AB')
    if s[0] + s[-1] == 'BA':
        ba += 1
    if s[0] == 'B':
        b += 1
    if s[-1] == 'A':
        a += 1
ans += min(a, b)
if a == b == ba and b:
    ans -= 1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for _ in range(N)]
ans = 0
ba = b = a = 0
for s in S:
    ans += s.count('AB')
    if s[0] + s[-1] == 'BA':
        ba += 1
    if s[0] == 'B':
        b += 1
    if s[-1] == 'A':
        a += 1
ans += min([a, b])
if a == b == ba and b:
    ans -= 1
print(ans)

Submission status: Accepted

Solution code:
# N < 10000
N = int(input())

# len(s) < 10

count = 0
a, b, ba = 0, 0, 0
for i in range(N):
    s = input().rstrip()
    count += s.count("AB")

    if s[-1] == 'A':
        if s[0] == 'B':
            ba += 1
        else:
            a += 1
    elif s[0] == 'B':
        b += 1

#e = int(input())
#print("*A=",a, ", B*=",b, "B*A=",ba, ",AB=", count, ",expected=", e)

if ba > 1:
    count += ba - 1
    ba = 1

if a + b > 0:
    #count += max(min(a + ba, b),min (a, b + ba))
    count += min(a,b) + ba
print(count)

Submission status: Accepted

Solution code:
N=input()

ans=0
r_a_cnt=0
l_b_cnt=0
both=0

for _ in range(N):
	s=raw_input()
	if s[0]=="B" and s[-1]=="A": both+=1
	elif s[0]=="B": l_b_cnt+=1
	elif s[-1]=="A": r_a_cnt+=1

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

if l_b_cnt==r_a_cnt==0 and both>0:
	ans+=both-1
else:
	ans+=min( l_b_cnt+both , r_a_cnt+both)

print ans

Submission status: Accepted

Solution code:
N=int(input())
countab,counta,countb,count=0,0,0,0
for i in range(N):
	s=input()
	if (s[0]=='B')&(s[-1]!='A'):
		countb+=1
	if (s[-1]=='A')&(s[0]!='B'):
		counta+=1
	if (s[0]=='B')&(s[-1]=='A'):
		count+=1
	countab+=s.count('AB')
if count==0: print(min(counta,countb)+countab)
elif counta+countb==0: print(count-1+countab)
else: print(min(counta,countb)+countab+count)

Submission status: Accepted

Solution code:
from collections import defaultdict
import math


def kari():
    map(int, input().split())
    list(map(int, input().split()))
    math.ceil()

def main():
    num = int(input())
    data = [input() for i in range(num)]
    count = 0
    for i in range(num):
        count += data[i].count('AB')

    count_a, count_b, ryouhou = 0, 0, 0
    for i in range(num):
        if data[i][0] == 'B' and data[i][-1] == 'A':
            ryouhou += 1
        elif data[i][0] == 'B':
            count_b += 1
        elif data[i][-1] == 'A':
            count_a += 1

    # print(count, count_a, count_b, ryouhou)

    if count_a > 0 and count_b > 0:
        count_a -= 1
        count_b -= 1
        count += ryouhou + 1 + min(count_a, count_b)
    elif count_a > 0 or count_b > 0:
        count += ryouhou
    else:
        count += max(0, ryouhou - 1)


    # count += min(count_a, count_b)
    print(count)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar  1 19:29:34 2019

@author: nakamuratakayuki
"""
N = int(input())
S = []
for i in range(N):
    S.append(input())

m = 0
f = 0
b = 0
t = 0
for s in S:
    if s.startswith('B'):
        m += 1
    if s.endswith('A'):
        f += 1
    if s.startswith('B')*s.endswith('A'):
        m -= 1
        f -= 1
        b += 1
    t += s.count('AB')
if f == 0 and m == 0:
    b -= 1
ans = min(f,m)+max(b,0)+t

print(max(ans,0))