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)]

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

p = min([ba, a, b])
ab += 2*p
ba -= p
a -= p
b -= p

if ba == 0:
    ab += min([a, b])
else:
    ab += ba
    if p == 0 and a == 0 and b == 0:
        ab -= 1

print(ab)

Submission status: Accepted

Solution code:
N=int(input())
list=[]
for x in range(N):
    list.append(input())
count=0
acount=0
bcount=0
abcount=0
for c in range(N):
    count=count+list[c].count('AB')
    if list[c][0]=='B':
        bcount=bcount+1
        if list[c][-1]=='A':
            abcount=abcount+1
    if list[c][-1]=='A':
        acount=acount+1
xx=min(acount,bcount)
if abcount==acount==bcount:
    if abcount==0:
        print(count+xx)
    else:
        print(count+xx-1)
else:
    print(count+xx)

Submission status: Accepted

Solution code:
n = int(input())
cnt = 0
ca = 0
cb = 0
cab = 0

for i in range(n):
    s = input()
    cnt += s.count('AB')
    if s[-1] == 'A':
        ca += 1
    if s[0] == 'B':        
        cb += 1
    if s[-1] == 'A' and s[0] == 'B':
        cab += 1

m1 = min(ca, cb)
m2 = max(ca, cb)
if m2 == cab and cab != 0:
    m1 -= 1
print(cnt+m1)

Submission status: Accepted

Solution code:
N = int(input())
s = [input() for i in range(N)]
count = 0
flag = 1
a_count = 0
b_count = 0
for i in range(N):
    count += s[i].count('AB')
    if s[i][0]=='B' and s[i][-1]!='A':
        flag = 0
    if s[i][0]!='B' and s[i][-1]=='A':
        flag = 0
    if s[i][0]=='B':
        b_count += 1
    if s[i][-1] =='A':
        a_count += 1

if a_count >0 and b_count > 0:
    count += min(a_count, b_count)-flag

print(count)

Submission status: Accepted

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

enda = 0
startb = 0
btoa = 0
ans = 0

for i in s:
    if i[0] == 'B' and i[-1] == 'A':
        btoa += 1
    elif i[-1] =='A':
        enda += 1
    elif i[0] == 'B':
        startb += 1
    ans += i.count('AB')

# print('-a:', enda, 'b-:', startb, 'b-a:', btoa, 'ans:',ans)

if btoa >= 1:
    ans += btoa - 1
    btoa = 1
    if enda > 0 and startb > 0:
        ans += 2
        btoa = 0
        enda -= 1
        startb -= 1
    elif enda > 0:
        ans += 1
        enda -= 1
    elif startb > 0:
        ans += 1
        startb -= 1

if enda < startb:
    enda, startb = startb, enda
ans += startb
enda -= startb
startb = 0

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
"""<https://github.com/cheran-senthil/PyRival>"""
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    _str = str
    str = lambda x=b"": x if type(x) is bytes else _str(x).encode()


def main():
    n = int(input())

    a = b = c = m = 0

    for i in range(n):
        s = input()
        m += s.count('AB')

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

    if c and a:
        a -= 1
        m += 1

    if c and b:
        b -= 1
        m += 1

    m += max(0, c - 1) + min(a, b)

    print(m)


# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._buffer = BytesIO()
        self._fd = file.fileno()
        self._writable = "x" in file.mode or "r" not in file.mode
        self.write = self._buffer.write if self._writable else None

    def read(self):
        if self._buffer.tell():
            return self._buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self._buffer.tell()
            self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
        self.newlines -= 1
        return self._buffer.readline()

    def flush(self):
        if self._writable:
            os.write(self._fd, self._buffer.getvalue())
            self._buffer.truncate(0), self._buffer.seek(0)


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()


sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")

# endregion

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N=int(input())
K=[]
ans=0
ans2=0
AA=0
BB=0
BA=0
for i in range(N):
    s=input().strip()
    ans+=s.count('AB')
    ans2+=s.count('AB')
    if s[0]=='B' and s[-1]=='A':
        BA+=1
    elif s[0]=='B':
        BB+=1
    elif s[-1]=='A':
        AA+=1
#strategy1        
tmp=min(AA,BB)
tmp2=max(AA-tmp, BB-tmp)
tmp3=min(BA,tmp2)
if tmp3==BA:
    tmp4=0
elif tmp3==tmp2 and tmp2!=0:
    tmp4=(BA-tmp3)
elif tmp3==tmp2 and tmp2==0:
    tmp4=(BA-tmp3)-1
ans=ans+tmp+tmp3+tmp4
#strategy2
ans2+=BA
if BA>0:
    ans2-=1
if BA>0:
    if BB>0:
        BB-=1
        ans2+=1
    if AA>0:
        AA-=1
        ans2+=1
kk=min(BB,AA)
if kk>0:
    ans2+=kk
#print(ans,ans2)
print(max(ans,ans2))

Submission status: Accepted

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

ans = 0
num_a = 0
num_b = 0
num_ba = 0
num_ab = 0
for i in s:
    if(i[-1]=='A' and i[0]=='B'):
        num_ba += 1
    elif(i[-1]=='A'):
        num_a+=1
    elif(i[0]=='B'):
        num_b+=1
    last = ''
    for k in i:
        if(k=='A'):
            last = 'A'
        elif(last == 'A' and k=='B'):
            num_ab += 1
            last = ''
        else:
            last = ''

ans += num_ab

num_conn = min(num_a,num_b)
if(num_a!=num_b and num_ba!=0):
    ans+=num_ba+num_conn
elif(num_ba==0):
    ans+=num_conn
elif(num_a==0 and num_b==0):
    ans+=num_ba-1
else:
    ans+=num_ba+num_conn
print(ans)

Submission status: Accepted

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

mod = 10**9+7

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


if BA_cnt != 0 and A_cnt == 0 and B_cnt == 0:
    plus = BA_cnt - 1
elif BA_cnt != 0 and A_cnt == 0:
    plus = min(BA_cnt,BA_cnt+B_cnt)
elif BA_cnt != 0 and B_cnt == 0:
    plus = min(BA_cnt,BA_cnt+A_cnt)
else:
    plus = min(BA_cnt+A_cnt,BA_cnt+B_cnt)

cnt += plus

print(cnt)

Submission status: Accepted

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]


N = int(input())

head_b_count = 0
tail_a_count = 0

head_b_tail_a_count = 0

total = 0

for _ in range(N):

    s = input()

    if s[0] == 'B':
        head_b_count += 1
    if s[-1] == 'A':
        tail_a_count += 1
    if s[0] == 'B' and s[-1] == 'A':
        head_b_tail_a_count += 1

    total += s.count('AB')

additional = min(head_b_count, tail_a_count)

if head_b_count == tail_a_count == head_b_tail_a_count != 0:
    additional -= 1

total += additional

print(total)

Submission status: Accepted

Solution code:
N = int(input())

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

    if S[-1] == "A" and S[0] == "B":
        dic2["AB"] += 1
    elif S[-1] == "A":
        dic2["A"] += 1
    elif S[0] == "B":
        dic2["B"] += 1

if dic2["A"] == 0 and dic2["B"] == 0:
    print(ans + max(dic2["AB"] - 1, 0))
else:
    print(ans + min(dic["A"], dic["B"]))

Submission status: Accepted

Solution code:
N = int(input())
numofAB = 0
numofLastA = 0
numofStartB = 0
numofLastAandStartB = 0
for _ in range(N):
    IN = input()
    numofAB += IN.count('AB')
    if IN[0] == 'B':
        numofStartB += 1
    if IN[-1] == 'A':
        numofLastA += 1
    if IN[0] == 'B' and IN[-1] == 'A':
        numofLastAandStartB += 1

numofLastA -= numofLastAandStartB
numofStartB -= numofLastAandStartB

if numofLastA > numofStartB:
    numofAB += numofStartB + numofLastAandStartB
else:
    numofAB += numofLastA + numofLastAandStartB
if numofLastA == 0 and numofStartB == 0 and numofLastAandStartB>0 :
    numofAB -= 1

print("{}".format(numofAB))

Submission status: Accepted

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

cnt = 0
head_b_cnt = 0
end_a_CNT = 0
head_a_end_b_cnt = 0
for word in s:
    cnt += word.count('AB')
    if word[0] == 'B':
        head_b_cnt += 1
    if word[-1] == 'A':
        end_a_CNT += 1
    if word[0] == 'B' and word[-1] == 'A':
        head_a_end_b_cnt += 1

if (head_b_cnt ==  end_a_CNT ==  head_a_end_b_cnt and head_a_end_b_cnt > 0):
    cnt += min(head_b_cnt, end_a_CNT) - 1
else:
    cnt += min(head_b_cnt, end_a_CNT)

print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
B = 0
A = 0
AB = 0
count = 0

for _ in range(n):
    line = list(input())
    for i in range(len(line)-1):
        if line[i] == 'A' and line[i+1] == 'B':
            count += 1
    if line[0] == 'B' and line[len(line)-1] == 'A':
        AB += 1
    elif line[0] == 'B':
        B += 1
    elif line[len(line)-1] == 'A':
        A += 1


if AB > 1:
    count += AB - 1
    if A > 0:
        count += 1
    if B > 0:
        count += 1
    if A-1 > 0 and B-1 > 0:
        count += min([A-1,B-1])
elif AB == 1:
    if A > 0:
        count += 1
    if B > 0:
        count += 1
    if A-1 > 0 and B-1 > 0:
        count += min([A-1,B-1])
else:
    count += min([A,B])

print(count)

Submission status: Accepted

Solution code:
#https://atcoder.jp/contests/diverta2019/tasks/diverta2019_c

N = int(input())
s = []
for i in range(N):
    s.append(list(str(input())))

flag = False
count = 0
for i in range(len(s)):
    flag = False
    for j in range(len(s[i])):
        if flag == True and s[i][j] == 'B':
            count += 1
            flag = False
        elif s[i][j] == 'A':
            flag = True
        else:
            flag = False

#print(count)

startcnt = [0] * N
endcnt = [0] * N
for i in range(len(s)):
    if s[i][0] == 'B':
        startcnt[i] = 1
    if s[i][len(s[i])-1] == 'A':
        endcnt[i] = 1

#print(startcnt,endcnt)

cntpls = [0,0,0] #始め、終わり、両方
for i in range(N):
    if startcnt[i] == 1 and  endcnt[i] == 0:
        cntpls[0]+= 1
    elif startcnt[i] == 0 and  endcnt[i] == 1:
            cntpls[1] += 1
    elif startcnt[i] == 1 and  endcnt[i] == 1:
        cntpls[2] += 1

#print(cntpls)

add = 0
if cntpls[2] > 0:
    count += cntpls[2] - 1
    if cntpls[1] >= 1:
        add += 1
        cntpls[1] -= 1

    if cntpls[0] >= 1:
        add += 1
        cntpls[0] -= 1

print(count + add + min(cntpls[0],cntpls[1]))

Submission status: Accepted

Solution code:
N = int(input())
ss = 0
sl = 0
ssl = 0
cou = 0
for i in range(N):
    s = input()
    cou += s.count("AB")
    if s[0] == "B" and s[-1] != "A":
        ss += 1
    if s[-1] == "A" and s[0] != "B":
        sl += 1
    if s[0] == "B" and s[-1] == "A":
        ssl += 1
if ssl == 0 and ss == 0 and sl == 0:
    print(cou)
elif ssl != 0 and ss == 0 and sl == 0:
    print(cou + ssl -1)
elif ssl != 0 and ss != 0 and sl == 0:
    print(cou + ssl)
elif ssl != 0 and ss == 0 and sl != 0:
    print(cou + ssl)
else:
    print(cou + ssl + 1 + min(ss - 1, sl - 1))

Submission status: Accepted

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

b,a = sorted([a,b])
if ab > 0:
    ans += ab-1
    ab = 1
if a > 0:
    ans += ab
ans += b
print(ans)

Submission status: Accepted

Solution code:
#python 3.5.2

N = int(input())
s_list = [input() for i in range(N)]
cnt = sum([s.count("AB") for s in s_list])
a_end, b_start, a_b = 0, 0, 0

for s in s_list:
    if s[0] == "B" and s[-1] == "A":
        a_b += 1
    elif s[0] == "B":
        b_start += 1
    elif s[-1] == "A":
        a_end += 1
if a_b == 0:
    cnt += min(a_end, b_start)
else:
    cnt += a_b - 1
    if a_end >= 1:
        cnt += 1
        a_end -= 1
    if b_start >= 1:
        cnt += 1
        b_start -= 1
    cnt += min(a_end, b_start)
print(cnt)

Submission status: Accepted

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

n = int(input())

AB = 0
A = 0
B = 0
B_A = 0
for i in range(n):
    s = input()
    if s[0] == 'B' and s[-1] != 'A':
        B = B+1
    if s[0] != 'B' and s[-1] == 'A':
        A = A+1
    if s[0] == 'B' and s[-1] == 'A':
        B_A = B_A+1

    for j in range(len(s)-1):
        if s[j] == 'A' and s[j+1] == 'B':
            AB = AB + 1
ans = 0
if A>0:
    ans = B_A
    if B>0:
        ans = ans + 1
        if A-1>0 and B-1>0:
            ans = ans+min(A-1, B-1)

elif A == 0 and B_A>0:
    ans = B_A-1
    if B>0:
        ans = ans + 1
        if A-1>0 and B-1>0:
            ans = ans+min(A-1, B-1)

ans = ans + AB
print(ans)

Submission status: Accepted

Solution code:
import re


pattern = "AB"
num_input = int(input())

total_ab = 0

num_ab = 0
num_end_with_a = 0
num_start_with_b = 0
num_both = 0

prints = []

for i in range(0, num_input):
    input_string = input()
    num_ab += len(re.findall(pattern, input_string))
    start_with_b = (input_string[0] == 'B')
    end_with_a = (input_string[-1] == 'A')

    if start_with_b and end_with_a:
        num_both += 1
    elif start_with_b:
        num_start_with_b += 1
    elif end_with_a:
        num_end_with_a += 1

# print(num_ab, num_both, num_start_with_b, num_end_with_a)

# add in-string 'AB'
total_ab += num_ab

# consume both first

# do setup, for case of '--A's or 'B--'s not exist
if num_end_with_a == 0 and num_start_with_b == 0:
    if num_both >= 2:
        num_both -= 2
        num_end_with_a += 1
        num_start_with_b += 1

elif min(num_end_with_a, num_start_with_b) == 0:
    if num_both >= 1:
        if num_end_with_a == 0:
            num_both -= 1
            num_end_with_a += 1
        
        if num_start_with_b == 0:
            num_both -= 1
            num_start_with_b += 1

# then consume
if num_both > 0:
    total_ab += (num_both+1)
    num_end_with_a -= 1
    num_start_with_b -= 1

# then consume other '--A's  and 'B--'s
total_ab += min(num_start_with_b, num_end_with_a)

print(total_ab)
exit(0)

Submission status: Accepted

Solution code:
import re

N = int(input())

cnt = 0
tail_A = 0
head_B = 0
both = 0

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

if tail_A == 0 and head_B == 0 and both == 0:
    cnt = cnt
elif tail_A == both and head_B == both:
    cnt += min(tail_A, head_B) - 1
else:
    cnt += min(tail_A, head_B)


print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
s = []
ans = 0
c = [0, 0, 0]
for _ in range(n):
    tmp = input()
    if tmp[0] == "B" and tmp[-1] == "A":
        c[2] += 1
    elif tmp[0] == "B":
        c[1] += 1
    elif tmp[-1] == "A":
        c[0] += 1
    for i in range(len(tmp) - 1):
        if tmp[i:i+2] == "AB":
            ans += 1

p = min(c[:-1])
ans += p
p = max(c[:-1])-p
if c[0] == 0 and c[1] == 0:
    ans += max(c[2]-1, 0)
else:
    ans += c[2]
print(ans)

Submission status: Accepted

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

#読み込み
n = int(input())

strs = []

for i in range(n):
    strs.append(input())

#文字列の確認
str_in_num = 0
str_both_ab = 0
str_head_a = 0
str_tail_b = 0

for st in strs:
    #文字列中にABを含むもの
    #print(st)
    if len(st) > 2:
        str_in_num += st[0:-1].count('AB')

    #文字列の先頭がBのもの
    if st[-1] == 'A' and st[0] == 'B':
        str_both_ab += 1
    else:
        if st[-1] == 'A':
            str_head_a += 1

        if st[0] == 'B':
            str_tail_b += 1

total = 0

if str_both_ab > 0:
    total += (str_both_ab - 1)

    if str_head_a > 0:
        total += 1
        str_head_a -= 1
    if str_tail_b > 0:
        total += 1
        str_tail_b -= 1

total += str_in_num
total += min(str_head_a, str_tail_b)

print(total)

Submission status: Accepted

Solution code:
N=int(input())

b_a=0
_a=0
b_=0
ans=0

for i in range(N):
    s=input()
    if s[0]=='B' and s[-1]=='A':
        b_a+=1
    elif s[0]=='B':
        b_+=1
    elif s[-1]=='A':
        _a+=1

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

if b_a>0:
    ans+=b_a-1
    if _a==0 and b_==0:
        print(ans)
    elif _a==1 and b_==0:
        print(ans+1)
    elif _a==1 and b_==0:
        print(ans+1)
    elif _a==1 and b_==1:
        print(ans+2)
    else:
        print(ans+2+min(_a-1,b_-1))
else:
    print(ans+min(_a,b_))

Submission status: Accepted

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


def main():
  lines = [input().strip() for _ in range(int(input()))]
  types = [(int(s[0] == 'B'), int(s[-1] == 'A')) for s in lines]
  count = sum(s.count('AB') for s in lines)

  before = sum(t[0] for t in types)
  after = sum(t[1] for t in types)

  if (0, 1) not in types:
    before -= 1

  if (1, 0) not in types:
    after -= 1

  before = max(before, 0)
  after = max(after, 0)

  print(count + min(before, after))


if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
import sys

stdin = sys.stdin

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

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

Submission status: Accepted

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

import numpy as np

N = int(input())
S_list = [input().rstrip() for _ in range(N)]

S_ab_number = [i.count('AB') for i in S_list]
S_b_start_number = [1 if i[0] == 'B' and i[-1] != 'A' else 0 for i in S_list]
S_a_end_number = [1 if i[-1] == 'A' and i[0] != 'B' else 0 for i in S_list]
S_both_number = [1 if i[-1] == 'A' and i[0] == 'B' else 0 for i in S_list]

if sum(S_both_number) == 0:
    print(sum(S_ab_number) +  min(sum(S_b_start_number),sum(S_a_end_number)))
elif sum(S_b_start_number) == 0 and sum(S_a_end_number) != 0:
    print(sum(S_ab_number) + sum(S_both_number))
elif sum(S_b_start_number) != 0 and sum(S_a_end_number) == 0:
    print(sum(S_ab_number) + sum(S_both_number))
elif sum(S_b_start_number) == 0 and sum(S_a_end_number) == 0:
    print(sum(S_ab_number) + sum(S_both_number) - 1)
else:
    print(sum(S_ab_number) + sum(S_both_number) + 1 + min(sum(S_b_start_number)-1,sum(S_a_end_number)-1))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())

a = 0
b = 0
ab = 0
count = 0
for i in range(n):
  line = input()
  count += line.count("AB")
  if line[0] == "B" and line[-1] == "A":
    ab += 1
  elif line[0] == "B":
    b += 1
  elif line[-1] == "A":
    a += 1

if ab > 0:
  count += ab - 1
  if a > 0:
    count += 1
    a -= 1
  if b > 0:
    count += 1
    b -= 1
count += min([a, b])
print(count)

Submission status: Accepted

Solution code:
# def gcd(a_gcd, b_gcd):
#     while b_gcd != 0:
#         a_gcd, b_gcd = b_gcd, a_gcd % b_gcd
#     return a_gcd
#
#
# def lcm(a_lcm, b_lcm):
#     return a_lcm * b // gcd(a_lcm, b_lcm)
#
#
# def max_sum(N_max_sum, a_max_sum):
#     dp = [0] * (N_max_sum + 1)
#     for i in range(N_max_sum):
#         dp[i + 1] = max(dp[i], dp[i] + a_max_sum[i])
#     return dp[N]
#
#
# def knapsack(N_knapsack, W, weight, value):
#     inf = float("inf")
#     dp = [[-inf for _ in range(W+1)] for j in range(N_knapsack + 1)]
#     for i in range(W+1):
#         dp[0][i] = 0
#
#     for i in range(N_knapsack):
#         for w in range(W+1):
#             if weight[i] <= w:
#                 dp[i+1][w] = max(dp[i][w-weight[i]]+value[i], dp[i][w])
#             else:
#                 dp[i+1][w] = dp[i][w]
#     return dp[N_knapsack][W]


# s = input()
N = int(input())
s = [input() for _ in range(N)]
# N, K = map(int, input().split())
# b = list(map(int, input().split()))
# c = [list(map(int, input().split())) for _ in range(N)]

ab_inner_count = 0
ab_top_bottom_count = 0
b_top_count = 0
a_bottom_count = 0
none_count = 0

for s_i in s:
    if s_i[0] == 'B' and s_i[-1] == 'A':
        ab_top_bottom_count += 1
    elif s_i[0] == 'B':
        b_top_count += 1
    elif s_i[-1] == 'A':
        a_bottom_count += 1
    else:
        none_count += 1

    for i in range(len(s_i) - 1):
        if s_i[i] == 'A' and s_i[i+1] == 'B':
            ab_inner_count += 1

ans = ab_inner_count

if ab_top_bottom_count == 0:
    ans += min(b_top_count, a_bottom_count)
elif a_bottom_count == 0:
    if b_top_count > 0:
        ans += ab_top_bottom_count
    else:
        ans += ab_top_bottom_count - 1
elif b_top_count == 0:
    if a_bottom_count > 0:
        ans += ab_top_bottom_count
    else:
        ans += ab_top_bottom_count - 1
else:
    ans += ab_top_bottom_count + 1
    ans += min(b_top_count - 1, a_bottom_count - 1)

print(ans)
# print(ab_top_bottom_count)
# print(a_bottom_count)
# print(b_top_count)

Submission status: Accepted

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

ans = 0
A = 0
B = 0
BA = 0
for i in s:
    ans += i.count("AB")
    if i[0:1] != "B" and i[-1:] == "A":
        A += 1
    elif i[0:1] == "B" and i[-1:] != "A":
        B += 1
    elif i[0:1] == "B" and i[-1:] == "A":
        BA += 1

#print(ans)
#print(A,B,BA)

while 1:
    if BA == 0 or A == B:
        break
    if A >= B:
        B += 1
    else:
        A += 1
    BA -= 1
#print(A,B,BA)
if A == 0 and B == 0:
    if BA != 0:    
        BA -= 1
print(ans + min(A,B) + BA)

Submission status: Accepted

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

if  t == b and a == t:
        d -= 1
if  t == 0 and a == 0 and b ==0:
        d += 1

print(d + c)

Submission status: Accepted

Solution code:
def solve():
    N = int(input())
    words = ["a"]*N
    for i in range(N):
        words[i] = list(input())
    A_list = []
    B_list = []
    AB_list = [] 
    AB_count = 0
    for i in range(N):
        tag_A = tag_B = tag_AB = 0
        for j in range(len(words[i])):
            if words[i][j] == "A" and j == len(words[i])-1:
                tag_A = 1
                tag_AB = 0
            elif words[i][j] == "A":
                tag_AB = 1
            elif words[i][j] == "B" and tag_AB == 1:
                tag_AB = 0
                AB_count += 1
            elif words[i][j] == "B" and j == 0:
                tag_B = 1
                tag_AB = 0
            else:
                tag_AB = 0
        if tag_A == 1 and tag_B == 1:
            AB_list.append(i)
        elif tag_A == 1:
            A_list.append(i)
        elif tag_B == 1:
            B_list.append(i)

    if len(AB_list) > 0 and len(A_list) > 0 and len(B_list) > 0:
        count = AB_count + len(AB_list) + min(len(A_list),len(B_list))
    elif len(AB_list) > 0 and len(A_list) == 0 and len(B_list) == 0:
        count = AB_count + len(AB_list) -1
    elif len(AB_list) > 0 and (len(A_list) == 0 or len(B_list) == 0):
        count = AB_count + len(AB_list)
    else:
        count = AB_count + min(len(A_list),len(B_list))

    print(count)


solve()

Submission status: Accepted

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

ans = 0
initb = 0
lasta = 0
add = 0
juuhuku = 0
flag = 0

for i in range(n):
    s[i] = input()
    st = s[i]

    if st[0] == "B":
        initb += 1

        if st[len(st)-1] == "A":
            lasta += 1
            juuhuku += 1
        else:
            flag += 1

    elif st[len(st)-1] == "A":
        lasta += 1
        flag += 1

    for j in range(len(st)):

        if st[j] == "A":

            if j == len(st) - 1:
                break
            if st[j+1] == "B":
                ans += 1

if initb <= lasta:
    add = initb
else:
    add = lasta

if juuhuku > 0:

    if flag > 0:
        ans = ans + add 
    else:
        ans = ans + add -1

else:
    ans = ans + add

print(ans)

Submission status: Accepted

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

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

	#print("{} {} {}".format(xA, Bx, BA))
	#print(ans)
	pls = 0
	if xA > 0 and Bx > 0:
		xA -= 1
		Bx -= 1

		pls = pls + 1 + BA
		BA = 0
	
	#print(pls)
	pls2 = 0
	if xA > 0 and Bx == 0 and BA > 0:
		xA -= 1
		pls2 = BA
		BA = 0
	
	#print(pls2)
	pls3 = 0
	if Bx > 0 and xA == 0 and BA > 0:
		Bx -= 1
		pls3 = BA
		BA = 0
	
	#print(pls3)
	pls4 = 0
	if Bx == 0 and xA == 0 and BA > 0:
		pls4 = BA - 1
		BA = 0
	
	#print(pls4)
	plspls = pls + pls2 + pls3 + pls4 + min(xA, Bx)
	#print(plspls)
	print(ans + min(plspls, N - 1))

	
if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
n = int(input())
S = []
ans = 0
numA = 0
numB = 0
numBA = 0
for _ in range(n):
    s = input()
    ans += s.count("AB")
    if s[-1] == "A":
        if s[0] == "B":
            numBA += 1
        else:
            numA += 1
    elif s[0] == "B":
        numB += 1

if numBA == 0:
    ans += min(numA, numB)
else:
    if numA > 0:
        if numB > 0:
            ans += numBA + 1 + min(numA - 1, numB - 1)
        else:
            ans += numBA
    else:
        if numB > 0:
            ans += (numBA - 1) + 1
        else:
            ans += numBA - 1

print(ans)

Submission status: Accepted

Solution code:
N=int(input())
s=' '
num_AB=0
num_A=0
num_B=0
num_A_and_B=0
for i in range(0,N):
    s=str(input())
    if(s[0]=='B' and s[-1]=='A'):
        num_A_and_B+=1
    elif(s[0]=='B'):
        num_B+=1
    elif(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
if(num_A_and_B>0):
    ans+=(num_A_and_B-1)
if(num_A_and_B>0 and num_A>0):
    num_A-=1
    ans+=1
if(num_A_and_B>0 and num_B>0):
    num_B-=1
    ans+=1
ans=ans+min(num_A,num_B)
print(ans)

Submission status: Accepted

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

if n == 1:
  print(cnt)
  exit()

if f >= 1:
  if a >= 1:
    cnt += 1
    a -= 1
  if b >= 1:
    cnt += 1
    b -= 1
print(cnt + max(0, f - 1) + min(a, b))

Submission status: Accepted

Solution code:
n = int(input())
s = [input() for u in range(n)]
a = sum([u.count("AB") for u in s])
b = len([1 for u in s if u.endswith("A")])
c = len([1 for u in s if u.startswith("B")])
d = len([1 for u in s if u.endswith("A") and u.startswith("B")])
if (b>0 and b==c and c==d):
  print(a+b-1)
else:
  print(a+min(b,c))

Submission status: Accepted

Solution code:
n = int(input())
x = 0
a = 0
b = 0
flag = True
for _ in range(n):
    s = input()
    if s[0] == 'B':
        b += 1
    if s[-1] == 'A':
        a += 1
    if s[0] == 'B' and s[-1] == 'A':
        pass
    elif s[0] == 'B' or s[-1] == 'A':
        flag = False
    for i in range(len(s)-1):
        if s[i:i+2] == 'AB':
            x += 1
if a == 0 or b == 0:
    print(x)
elif a == b and flag:
    print(x + a - 1)
else:
    print(x + min(a,b))

Submission status: Accepted

Solution code:
N = int(input())

minimum = 0
headB = 0
lastA = 0
both = 0

strs = []
for _ in range(N):
    s = input()
    minimum += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        both += 1
    else:
        if s[0] == 'B':
            headB += 1
        if s[-1] == 'A':
            lastA += 1

combi = 0
combi += min(lastA, headB)
lastA -= combi
headB -= combi

extra = 0
if lastA > 0:
    extra = min(lastA, both)
    lastA -= extra
    both -= extra
elif headB > 0:
    extra = min(headB, both)
    headB -= extra
    both -= extra

bonus = 0
if both > 0:
    if combi > 0 or extra > 0:
        bonus = both
    else:
        bonus = both-1

result = minimum + combi + extra + bonus

print(result)