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:
import sys
readline = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7

def main():
    N = int(readline())
    BX = 0
    XA = 0
    BA = 0
    AB = 0
    for _ in range(N):
        S = readline().decode('utf-8').strip()
        if S[0]=='B' and S[-1]=='A':
            BA += 1
        elif S[0]=='B':
            BX += 1
        elif S[-1] == 'A':
            XA += 1
        AB += S.count('AB')
    if BA==0:
        ans = AB + min(BX,XA)
    else:
        if XA+BX>0:
            ans = AB + BA + min(BX, XA)
        else:
            ans = AB + BA-1
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

#################

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

count = 0
enda = 0
startb = 0
both = 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':
            count += 1
    if s[i][-1] == 'A':
        enda += 1
    if s[i][0] == 'B':
        startb += 1
    if s[i][-1] == 'A' and s[i][0] == 'B':
        both += 1

temp = count+min(enda,startb)
if enda == startb == both and enda >= 1:
    temp -= 1
print(temp)

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline


def main():
    N = int(readline())
    cnt = 0; leftB = 0; rightA = 0; same = 0
    for _ in range(N):
        s = readline()[:-1]
        for i in range(len(s)-1):
            subs = s[i:i+2]
            cnt += subs == 'AB'
        leftB += s[0] == 'B'
        rightA += s[-1] == 'A'
        same += s[0] == 'B' and s[-1] == 'A'
    
    if same == leftB == rightA:
        ans = cnt + max(min(N-1, same-1), 0)
    else:
        ans = cnt + min(N-1, leftB, rightA)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n=int(input())
s=[input() for i in range(n)]
lastA=0
firstB=0
lastAandfirstB=0
ABs=0
for si in s:
    ABs+=si.count("AB")
    firstB+=(si[0]=="B")
    lastA+=(si[-1]=="A")
    lastAandfirstB+=(si[0]=="B")*(si[-1]=="A")

can=min(firstB,lastA)
# print(lastA,firstB,lastAandfirstB)
# if lastAandfirstB==1 and firstB==1 and lastA==1:
#     print(ABs)
#     exit()
if can==n or lastAandfirstB==firstB==lastA!=0:
    can=can-1
print(can+ABs)

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
sb = []
fa = []

def ABCount(s):
    cnt = 0
    for i in range(len(s)-1):
        if s[i] == "A" and s[i+1] == "B":
            cnt += 1
    return cnt

for i in range(n):
    s = input()
    ans += ABCount(s)
    if s[0] == "B":
        sb.append(i)
    if s[-1] == "A":
        fa.append(i)

if len(sb) == len(fa) and len(sb) > 0:
    sb.sort()
    fa.sort()
    f = False
    for i in range(len(sb)):
        if not sb[i] == fa[i]:
            f = True
            break
    if f:
        ans += len(sb)
    else:
        ans += len(sb)-1
else:
    ans += min(len(sb),len(fa))

print(ans)

Submission status: Accepted

Solution code:
n=int(input())
s=[None]*n
nA=0
nB=0
nAB=0
ans=0
for i in range(n):
    ss = input()
    ans+= ss.count("AB")
    if ss[0]=="B" and ss[-1]=="A":
        nAB+=1
    elif ss[0]=="B":
        nB+=1
    elif ss[-1]=="A":
        nA+=1
    s[i]=ss

if nAB==0:
    ans+=min(nA,nB)
elif nA==0 and nB==0:
    ans+=nAB-1
elif nA==0:
    ans+=nAB
elif nB==0:
    ans+=nAB
else:
    ans+=nAB+1 + min(nA,nB)-1
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())
r = 0
a = 0
b = 0
ab = 0
for _i in range(n):
    s = input()
    r += s.count("AB")
    B = 0
    A = 0
    if s[-1]=="A":
        a += 1
    if s[0]=="B":
        b += 1
    if s[-1]=="A" and s[0]=="B":
        ab += 1
if ab == a and ab == b:
    print(r+max(0, ab-1))
else:
    print(r+min(a, b))

Submission status: Accepted

Solution code:
N = int(input())

ends_with_A = 0
starts_with_B = 0
both = 0

count = 0

for _ in range(N):
  s = input()
  count += s.count('AB')
  if s.endswith('A') and s.startswith('B'):
    both += 1
  elif s.endswith('A'):
    ends_with_A += 1
  elif s.startswith('B'):
    starts_with_B += 1

# 結合した文字が AXXXXXX or XXXXXXXB となるとき     
if ends_with_A + starts_with_B > 0:
  print(count + both + min(ends_with_A, starts_with_B))
else:  
  print(count + max(both - 1, 0) + min(ends_with_A, starts_with_B))

Submission status: Accepted

Solution code:
#!/usr/bin/python3

import sys
sys.setrecursionlimit(10 ** 5 + 10)
def input(): return sys.stdin.readline().strip()

def resolve():
    
    N=int(input())
    x=0
    y=0
    z=0
    cnt=0
    for i in range(N):
        s=str(input())
        if s[0]=='B' and s[-1]=='A':
            x+=1
        if s[0]=='B' and s[-1]!='A':
            y+=1
        if s[0]!='B' and s[-1]=='A':
            z+=1

        
        for j in range(len(s)-1):
            if s[j:j+2]=='AB':
                cnt+=1
    if x==0:
        print(cnt+min(y,z))
    elif y>0 or z>0: print(cnt+(x-1)+min(y,z)+1)
    else: print(cnt+(x-1)+min(y,z))    
        

    
resolve()

Submission status: Accepted

Solution code:
n = int(input())
s = []
for _ in range(n):
    s.append(input())
a = 0
b = 0
ans = 0
same = 0
for i in s:
    flg = False
    if i[0]=='B':
        flg = True
        b += 1
    if i[-1]=='A':
        a += 1
        if flg:
            same += 1
    for j in range(len(i)-1):
        if i[j:j+2]=='AB':
            ans += 1
ans += min(a, b)
if a == b == same > 0:
    ans -= 1
print(ans)

Submission status: Accepted

Solution code:
from collections import Counter

DEBUG = False

N = int(input())
S = []
patterns = []
ans = 0
for _ in range(N):
    s = input()
    # S.append(s)
    ans += s.count("AB")
    # 3進数表記 -> 1bit目: 先頭の文字, 2bit目: 末尾の文字
    # A = 0, B = 1, O:other = 2
    # A...A: 0, A...B: 1, A...O: 2
    # B...A: 3, B...B: 4, B...O: 5
    # O...A: 6, O...B: 7, O...O: 8
    pattern = ""
    pattern += "2" if (s[0] != "A"  and s[0] != "B") else "1" if s[0] == "B" else "0"
    pattern += "2" if (s[-1] != "A" and s[-1] != "B") else "1" if s[-1] == "B" else "0"
    patterns.append(int(pattern, 3))
    if DEBUG:
        print("s: {}, pattern: {}".format(s, pattern))

if DEBUG:
    print("patterns: {}".format(patterns))
    print("ans: {}".format(ans))

counter = Counter(patterns)
if DEBUG:
    print("counter: {}".format(counter))

ans += counter[3] - 1 if counter[3] else 0
if DEBUG:
    print("ans: {}".format(ans))


num_tail_A = counter[0] + counter[6]
num_head_B = counter[4] + counter[5]
if DEBUG:
    print("num_tail_A: {}, num_head_B: {}".format(num_tail_A, num_head_B))

if not num_tail_A and not num_head_B:
    pass
else:
    num_tail_A += 1 if counter[3] else 0
    num_head_B += 1 if counter[3] else 0
    ans += min(num_tail_A, num_head_B)

print(ans)

Submission status: Accepted

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

fi = 0
sec = 0
thi = 0
forth = 0

for i in range(n):
    cnt =  s[i].count("AB")
    if cnt>=1:
        fi+=cnt

    syo = s[i][0]
    saigo = s[i][-1]

    if syo =="B" and saigo == "A":
        sec+=1
    elif syo == "B":
        thi+=1
    elif saigo=="A":
        forth+=1

su=0
if sec>=1:
    su += sec-1

su+=fi

if sec>=1:
    su+=min(1,thi)
    su+=min(1,forth)
    su+=min(thi-min(1,thi),forth-min(1,forth))
else:
    su+=min(thi,forth)

#print(fi,sec,thi,forth)
print(su)

Submission status: Accepted

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

cnt = 0
end_a = 0
sta_b = 0
a_b = 0
for s in S:
    cnt += s.count('AB')
    if s[-1]=='A' and s[0]=='B':
        a_b += 1
    elif s[-1]=='A':
        end_a += 1
    elif s[0]=='B':
        sta_b += 1
if a_b>=1:
    cnt += a_b-1
    if end_a>=1:
        end_a -= 1
        cnt += 1
    if sta_b>=1:
        sta_b -=1
        cnt+=1
cnt += min(end_a, sta_b)

print(cnt)

Submission status: Accepted

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

cnt = sum(map(lambda x: x.count('AB'), S))
B_A = len(list(filter(lambda x: x[0] == 'B' and x[-1] == 'A', S)))
B__ = len(list(filter(lambda x: x[0] == 'B' and x[-1] != 'A', S)))
__A = len(list(filter(lambda x: x[0] != 'B' and x[-1] == 'A', S)))

if B_A == 0:
    print(cnt + min(B__, __A))
else:
    if B__ + __A > 0:
        print(cnt + B_A + min(B__, __A))
    else:
        print(cnt + B_A - 1)

Submission status: Accepted

Solution code:
n=int(input())
xa=0
bx=0
ba=0
ans=0
for i in range(n):
    l=list(input())
    for j in range(len(l)-1):
        if l[j]=='A' and l[j+1]=='B':
            ans += 1
    if l[0]=='B':
        if l[len(l)-1]=='A':
            ba += 1
        else:
            bx += 1
    elif l[len(l)-1]=='A':
        xa += 1
if ba>0:
    ans += ba-1
    if xa>0:
        ans += 1
        xa -= 1
    if bx>0:
        ans += 1
        bx -= 1
ans += min(xa,bx)
print(ans)

Submission status: Accepted

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

a = 0
b = 0
ab = 0
ans = 0
for s in S:
    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
    else:
        pass
if ab:
    ans += ab-1
if ab:
    if a:
        ans += 1
        a -= 1
    if b:
        ans += 1
        b -= 1
ans += min(a, b)
print(ans)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

def diverta19_c():
    _ = int(readline())
    S = [ln.strip().decode('UTF-8') for ln in read().split()]

    # _AB_ , B_A , B_ , _A の個数をそれぞれ数える
    inner, st, ed, sted = 0, 0, 0, 0
    for si in S:
        inner += si.count('AB')
        if si[0] == 'B' and si[-1] == 'A': sted += 1
        elif si[0] == 'B': st += 1
        elif si[-1] == 'A': ed += 1

    ans = inner  # これは確定
    if sted > 0:
        ans += (sted - 1)  # x個でx-1組のABができる
        if st > 0:
            ans += 1  # B_A + B_ で1組
            st -= 1
        if ed > 0:
            ans += 1  # _A + B_A で1組
            ed -= 1
    ans += min(st, ed)  # _A + B_ で1組
    print(ans)

diverta19_c()

Submission status: Accepted

Solution code:
import sys

stdin = sys.stdin
inf = 1 << 60
mod = 1000000007

sys.setrecursionlimit(10 ** 7)

ni      = lambda: int(ns())
nin     = lambda y: [ni() for _ in range(y)]
na      = lambda: list(map(int, stdin.readline().split()))
nan     = lambda y: [na() for _ in range(y)]
nf      = lambda: float(ns())
nfn     = lambda y: [nf() for _ in range(y)]
nfa     = lambda: list(map(float, stdin.readline().split()))
nfan    = lambda y: [nfa() for _ in range(y)]
ns      = lambda: stdin.readline().rstrip()
nsn     = lambda y: [ns() for _ in range(y)]
ncl     = lambda y: [list(ns()) for _ in range(y)]
nas     = lambda: stdin.readline().split()

from collections import defaultdict

n = ni()
s = nsn(n)

cnt = 0
dcnt = 0
dic = defaultdict(int)
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
    dic['A'] += (s[i][-1] == 'A')
    dic['B'] += (s[i][0] == 'B')
    dcnt += s[i][-1] == 'A' and s[i][0] == 'B'

ans = min(dic['A'], dic['B'])
if dcnt >= 1 and max(dic['A'], dic['B']) == dcnt:
    print(ans - 1 + cnt)
else:
    print(ans + cnt)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
inf = float('inf')
ninf = -float('inf')
 
#整数input
def ii(): return int(sys.stdin.readline().rstrip()) #int(input())
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) #list(map(int,input().split()))
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]
#文字列input
def ss(): return sys.stdin.readline().rstrip() #input()
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) #list(input().split())
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]

#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？

n=ii()
backa=0
frontb=0
backafrontb=0
ans=0
for i in range(n):
    s=list(ss())
    for j in range(len(s)-1):
        if s[j]+s[j+1]=="AB":
            ans+=1
    if s[0]=="B" and s[-1]=="A":
        backafrontb+=1
    elif s[0]=="B":
        frontb+=1
    elif s[-1]=="A":
        backa+=1
#print(backa,frontb,backafrontb,ans)

if backafrontb>0:
    ans+=backafrontb-1

    if backa>0:
        ans+=1 
        backa-=1
    if frontb>0:
        ans+=1
        frontb-=1
    ans+=min(backa,frontb)
else:
    ans+=min(backa,frontb)


print(ans)

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
tail_a_cnt = 0
top_b_cnt = 0
top_b_tail_a = 0
for i in range(n):
    s = list(input())
    top_b = False
    tail_a = False
    
    for c in range(len(s)):
        if c == 0:
            if s[c] == 'B':
                top_b = True
        else:
            if s[c] == 'B' and s[c-1] == 'A':
                ans += 1
        
        if c == len(s)-1 and s[c]=='A':
            tail_a = True
            
    top_b_cnt += top_b
    tail_a_cnt += tail_a
    top_b_tail_a += top_b*tail_a
     
ans += min(top_b_cnt, tail_a_cnt)
if top_b_cnt == tail_a_cnt == top_b_tail_a and top_b_cnt>0:
    ans -= 1
    
print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
N=int(input())

ab=0
a=0
b=0
boa=0

for _ in range(N):
    s=input()
    ab+=s.count("AB")
    if s[0]=="B" and s[-1]=="A":
        boa+=1
    elif s[0]=="B":
        b+=1
    elif s[-1]=="A":
        a+=1
ans=ab

if boa>0:
    ans+=boa-1
    if b>0:
        ans+=1
        b-=1
    if a>0:
        ans+=1
        a-=1
ans+=min(a,b)
print(ans)

Submission status: Accepted

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


c = 0
ac = 0
bc = 0
abc = 0
for i in range(n):
    c += s[i].count('AB')
    if(s[i][-1] == 'A' and s[i][0] == 'B'):abc += 1
    elif(s[i][-1] == 'A'):ac += 1
    elif(s[i][0] == 'B'):bc += 1

if(abc == 0):
    print(c + min(ac,bc))
elif(ac + bc == 0):
    print(c + abc - 1)
else:
    print(c + abc + min(ac,bc))

Submission status: Accepted

Solution code:
n= int(input())
bdic = {'A':0,'B':1,'O':2}
aot = [[0 for i in range(3)] for i in range(3)]
ans=0
for i in range(n):
    s=input()
    subab=0
    for i in range(len(s)-1):
        if s[i]=='A' and s[i+1]=='B':subab+=1
    ans += subab
    f = 'O' if not s[0]  in bdic.keys() else s[0]
    l = 'O' if not s[-1] in bdic.keys() else s[-1]
    aot[bdic[f]][bdic[l]]+=1

oa = aot[bdic['O']][bdic['A']]+aot[bdic['A']][bdic['A']]
bo = aot[bdic['B']][bdic['O']]+aot[bdic['B']][bdic['B']]
ab = aot[bdic['A']][bdic['B']]
ba = aot[bdic['B']][bdic['A']]

if   oa==0 and bo==0:ans+=max(0,ba-1)
elif oa==0 and bo!=0:ans+=min(bo,ba)+max(0,ba-bo)
elif bo==0 and oa!=0:ans+=min(oa,ba)+max(0,ba-oa)
else:                ans+=min(oa,bo)+ba
print(ans)

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline


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

    xABx = 0
    xxxA = 0
    Bxxx = 0
    BxxA = 0
    for s in S:
        xABx += s.count("AB")
        if s[0] == "B" and s[-1] == "A":
            BxxA += 1
        elif s[0] == "B":
            Bxxx += 1
        elif s[-1] == "A":
            xxxA += 1

    if BxxA == 0:
        ans = xABx + min(xxxA, Bxxx)
    else:
        if xxxA == Bxxx == 0:
            ans = xABx + (BxxA - 1)
        else:
            ans = xABx + BxxA + min(xxxA, Bxxx)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()
def main():
    n=int(input())
    cunt_a=0
    cunt_b=0
    cunt_ba=0
    cunt_ab=0
    for i in range(n):
        s=input()
        if s[0]=='B' and s[-1]=='A':
            cunt_ba+=1
        elif s[0]=='B': 
            cunt_b+=1
        elif s[-1]=='A':
            cunt_a+=1
        for j in range(len(s)-1):
            if s[j:j+2]=="AB":
                cunt_ab+=1
    if cunt_a==0 and cunt_b==0 and cunt_ba>0:
        print(cunt_ab+cunt_ba-1)
    else:
        print(cunt_ab+cunt_ba+min(cunt_a,cunt_b))
    
if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
import sys
## io ##
def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
## dp ##
def DD2(d1,d2,init=0): return [[init]*d2 for _ in range(d1)]
def DD3(d1,d2,d3,init=0): return [DD2(d2,d3,init) for _ in range(d1)]
## math ##
def to_bin(x: int) -> str: return format(x, 'b') # rev => int(res, 2)
def to_oct(x: int) -> str: return format(x, 'o') # rev => int(res, 8)
def to_hex(x: int) -> str: return format(x, 'x') # rev => int(res, 16)
MOD=10**9+7
def divc(x,y) -> int: return -(-x//y)
def divf(x,y) -> int: return x//y
def gcd(x,y):
    while y: x,y = y,x%y
    return x
def lcm(x,y): return x*y//gcd(x,y)
def enumerate_divs(n):
    """Return a tuple list of divisor of n"""
    return [(i,n//i) for i in range(1,int(n**0.5)+1) if n%i==0]
def get_primes(MAX_NUM=10**3):
    """Return a list of prime numbers n or less"""
    is_prime = [True]*(MAX_NUM+1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(MAX_NUM**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i*2, MAX_NUM+1, i): is_prime[j] = False
    return [i for i in range(MAX_NUM+1) if is_prime[i]]
def prime_factor(n):
    """Return a list of prime factorization numbers of n"""
    res = []
    for i in range(2,int(n**0.5)+1):
        while n%i==0: res.append(i); n //= i
    if n != 1: res.append(n)
    return res
## libs ##
from itertools import accumulate as acc, combinations as combi, product, combinations_with_replacement as combi_dup
from collections import deque, Counter
from heapq import heapify, heappop, heappush
from bisect import bisect_left
#======================================================#

def main():
    n = II()
    ss = [IS() for i in range(n)]
    ab_type = {}
    ab_type['_ab_'] = 0
    ab_type['b__a'] = 0
    ab_type['___a'] = 0
    ab_type['b___'] = 0
    for s in ss:
        for i in range(len(s)-1):
            if s[i:i+2] == 'AB':
                ab_type['_ab_'] += 1
        if s[0] == 'B' and s[-1] == 'A':
            ab_type['b__a'] += 1
        elif s[-1] == 'A':
            ab_type['___a'] += 1
        elif s[0] == 'B':
            ab_type['b___'] += 1
    cnt = 0
    cnt += ab_type['_ab_']
    if ab_type['b__a'] > 0:
        cnt += ab_type['b__a']-1
        if ab_type['___a'] > 0:
            cnt += 1
            ab_type['___a'] -= 1
        if ab_type['b___'] > 0:
            cnt += 1
            ab_type['b___'] -= 1
    cnt += min(ab_type['___a'], ab_type['b___'])
    print(cnt)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

mid_ab = 0
la_fb = 0
last_a = 0
first_b = 0

for s in moji:
    mojiretu=len(s)
    if s[0] == 'B' and s[-1] == 'A':
        la_fb += 1
    elif s[0] == 'B':
        first_b += 1
    elif s[-1] == 'A':
        last_a += 1
    for j in range(mojiretu-1):
        if s[j] == 'A' and s[j+1] == 'B':
            mid_ab += 1

if la_fb == 0:
    ans = mid_ab+min(last_a,first_b)
elif last_a == first_b == 0 and la_fb> 0:
    ans = mid_ab+la_fb-1
else:
    if la_fb <= abs(last_a-first_b):
        ans = mid_ab+min(last_a,first_b)+la_fb
    else:
        ans = mid_ab+max(last_a,first_b)+(la_fb-abs(last_a-first_b))
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
a = 0
b = 0
ryou = 0
for _ in range(n):
    tmp = input()
    ans += tmp.count('AB')
    if tmp[0] == 'B':
        if tmp[-1] == 'A':
            ryou += 1
        else:
            b += 1
    elif tmp[-1] == 'A':
        a += 1

if ryou > 1:
    ans += (ryou-1)
    ryou = 1
if ryou == 1:
    if a >= 1:
        ans += 1
        a -= 1
    if b>=1:
        ans += 1
        b-=1
#print(ans)
ans += min(a,b)
#print(min(a,b))
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
cnt=0

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

if a==0 and b==0:print(cnt+max(0,c-1))
else:print(cnt+min(a,b)+c)

Submission status: Accepted

Solution code:
n=int(input())
cnt=0

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

if a==0 and b==0:print(cnt+max(0,c-1))
else:print(cnt+min(a,b)+c)

Submission status: Accepted

Solution code:
N = int(input())

prev_B = 0
back_A = 0
AB_num = 0
back_A_prev_B = 0
for i in range(N):
    s = input()
    if s[0] == "B":
        prev_B += 1
    if s[len(s)-1] == "A":
        back_A += 1
    if s[0] == "B" and s[len(s)-1] == "A":
        back_A_prev_B += 1
    for j in range(len(s)-1):
        if s[j] == "A" and s[j+1] == "B":
            AB_num += 1

if back_A_prev_B == prev_B and back_A_prev_B == back_A and back_A_prev_B != 0:
    print(AB_num + min(prev_B-1, back_A-1))
else:
    print(AB_num + min(prev_B, back_A))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
MOD = 10 ** 9 + 7
INF = 10 ** 11
import sys
sys.setrecursionlimit(100000000)

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

    cnt = 0
    ba = 0
    a = 0
    b = 0
    for s in S:
        for i in range(len(s) - 1):
            if s[i] == 'A' and s[i + 1] == 'B':
                cnt += 1
        if s[0] == 'B' and s[-1] == 'A':
            ba += 1
        elif s[0] == 'B':
            b += 1
        elif s[-1] == 'A':
            a += 1
    
    if a > 0 and b > 0:
        cnt += ba + 1 + min(a - 1,b - 1)
    elif a > 0:
        cnt += ba
    elif b > 0:
        cnt += ba
    else:
        if ba > 0:
            cnt += ba - 1
    print(cnt)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
a = 0
b = 0
ba = 0
ans = 0
for i 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 += min(a,b)
elif ba != 0:
    if a == 0 and b == 0:
        ans += ba-1
    else:
        ans += ba + min(a,b)
print(ans)

Submission status: Accepted

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

count = 0
xxxa = 0
bxxx = 0
bxxxa = 0
for st in s_l:
    if 'AB' in st:
        count += st.count('AB')
    if st.endswith('A'):
        if st.startswith('B'):
            bxxxa += 1
        else:
            xxxa += 1
    elif st.startswith('B'):
        bxxx += 1

if max(xxxa,bxxx) == 0:
    count += max(0, bxxxa - 1)
    print(count)
    exit()

while min(xxxa,bxxx,bxxxa) > 0:
    xxxa -= 1
    bxxx -= 1
    bxxxa -= 1
    count += 2
count += bxxxa
count += min(xxxa,bxxx)
print(count)

Submission status: Accepted

Solution code:
import re

n = int(input())
w = x = y = z = 0
for i in range(n):
    s = input()
    t = re.sub(r'AB', "X", s)
    w += len(s) - len(t)
    if s[0] == "B":
        if s[-1] == "A":
            x += 1
        else:
            y += 1
    elif s[-1] == "A":
        z += 1
if x > 1:
    w += x - 1
    x = 1
if max(x, y, z) == y:
    w += x
    w += z
elif max(x, y, z) == z:
    w += x
    w += y
print(w)

Submission status: Accepted

Solution code:
N = int(input())

ans = 0
tail_A = 0
head_B = 0
head_B_and_tail_A = 0

for i in range(N):
    s = str(input())
    ans += s.count("AB")

    if s[0]=="B":
        if s[-1]=="A":
            head_B_and_tail_A += 1
        else:
            head_B += 1
    elif s[-1]=="A":
        tail_A += 1

if head_B_and_tail_A >= 2:
    ans += head_B_and_tail_A - 1
    head_B_and_tail_A = 1

use_head_B_and_tail_A = min(head_B_and_tail_A,tail_A,head_B)
head_B_and_tail_A -= use_head_B_and_tail_A
tail_A -= use_head_B_and_tail_A
head_B -= use_head_B_and_tail_A
ans += 2*use_head_B_and_tail_A
#この段階でどれかは使い果たしている

use_num = min(head_B_and_tail_A,tail_A)
head_B_and_tail_A -= use_num
tail_A -= use_num
ans += use_num

use_num = min(head_B_and_tail_A,head_B)
head_B_and_tail_A -= use_num
head_B -= use_num
ans += use_num

use_num = min(tail_A,head_B)
#もう残りパターンは無いので算出の必要ないので省略
ans += use_num

print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

n = int(input())
strings = []
for _ in range(n):
    strings.append(input())

ans = 0
head_b = tail_a = both = 0
for s in strings:
    ans += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        both += 1
    elif s[0] == 'B':
        head_b += 1
    elif s[-1] == 'A':
        tail_a += 1

if both == 0:
    ans += min(head_b, tail_a)
elif head_b + tail_a == 0:
    ans += max(both - 1, 0)
else:
    ans += both + min(head_b, tail_a)
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
s=[input() for _ in range(n)]
ans=sum([si.count('AB') for si in s])
endA=len([si for si in s if si[-1]=='A'])
startB=len([si for si in s if si[0]=='B'])
AB=len([si for si in s if si[0]=='B' and si[-1]=='A'])
if endA*startB==0:
      print(ans)
elif AB==endA and AB==startB:
      print(ans+AB-1)
else:
      print(ans+min(endA,startB))

Submission status: Accepted

Solution code:
N = int(input())

ans = 0
top_b = 0
last_a = 0
top_b_and_last_a = 0

for _ in range(N):
    s = input()
    ans += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        top_b_and_last_a += 1
    elif s[0] == "B":
        top_b += 1
    elif s[-1] == "A":
        last_a += 1

ans += max(0, top_b_and_last_a - 1)
if top_b_and_last_a and top_b:
    top_b -= 1
    ans += 1
if top_b_and_last_a and last_a:
    last_a -= 1
    ans += 1
ans += min(top_b, last_a)

print(ans)

Submission status: Accepted

Solution code:
def solve():
    n = int(input())
    s = []
    ans = 0
    acnt = 0
    bcnt = 0
    bacnt = 0
    for i in range(n):
        s_i = input()
        ans += s_i.count('AB')
        s_i.replace('AB', '')
        if s_i[0] == 'B' and s_i[-1] == 'A':
            bacnt += 1
        elif s_i[0] == 'B':
            bcnt += 1
        elif s_i[-1] == 'A':
            acnt += 1

    # bacntをa,bに変換
    if bacnt == 0:
        ans += min(acnt, bcnt)
    elif acnt == 0 and bcnt == 0:
        ans += bacnt-1
    else:
        ans += bacnt + min(acnt, bcnt)

    print(ans)

solve()

Submission status: Accepted

Solution code:
n=int(input())
l=[0,0,0,0]#non,~a,b~,b~a
ans=0
for i in range(n):
    s=input()
    ans+=s.count("AB")
    l[2*int(s[0]=="B")+1*int(s[-1]=="A")]+=1

if l[-1]:
    ans+=l[-1]-1
    if l[1]:
        l[1]-=1
        ans+=1
    if l[2]:
        l[2]-=1
        ans+=1
print(ans+min(l[1:3]))