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 heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


def MI(): return map(int, input().split())


def S(): return input()


def MS(): return map(str, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


def print_matrix(mat):
    for i in range(len(mat)):
        print(*mat[i])


YNL = {False: 'No', True: 'Yes'}
YNU = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**10
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
# sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']


# show_flg = True
show_flg = False


def main():
    N = I()
    s = []

    for i in range(N):
        s.append(S())

    ans = 0
    a = 0
    b = 0
    dup = 0

    for i in range(N):
        if s[i][0] == 'B':
            b += 1
        if s[i][-1] == 'A':
            a += 1
        if s[i][0] == 'B' and s[i][-1] == 'A':
            dup += 1
        for j in range(1, len(s[i])):
            if s[i][j-1] == 'A' and s[i][j] == 'B':
                # print(j, s[i])
                ans += 1

    # print(dup, a, b, ans)
    if dup > 0 and dup == max(a, b):
        # print(dup, a, b)
        print(ans + dup - 1)
    else:
        print(ans + min(a, b))


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()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n = ni()
ans = 0
a=0
b=0
c=0

for i in range(n):
    s = ns()
    ans += 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

ans += min(n-1,a,b)+c
if a+b == 0 and c > 0:
    ans -= 1

print(ans)

Submission status: Accepted

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

acnt =0
bcnt =0
ecnt =0
cnt=0
nomal =0

for i in range(n):
    nomal += s[i].count('AB')
    t=0
    if s[i][0] == 'B':
        bcnt += 1
        cnt+=1
        t+=1
    if s[i][-1] == 'A':
        acnt += 1
        if not t:
            cnt+=1
        t+=1
    if t==2 :
        ecnt+=1

if cnt != 0 and cnt == ecnt:
    print(nomal + acnt-1)
else:
    print(nomal + min(acnt,bcnt))

Submission status: Accepted

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

Submission status: Accepted

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

n = int(input())

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

ab = 0 # ABが内部にあるもの
tail_a = 0 # 末尾がAのもの
head_b = 0 # 先頭がBのもの
both = 0
for s in strings:
    ab += s.count('AB')
    if s[-1] == 'A' and s[0] != 'B':
        tail_a += 1
    if s[0] == 'B' and s[-1] != 'A':
        head_b += 1
    if s[-1] == 'A' and s[0] == 'B':
        both += 1
ans = ab 
if both == 0:
    ans += min(tail_a, head_b)
elif tail_a + head_b > 0:
    ans += both + min(tail_a, head_b)
elif tail_a == 0 and head_b == 0:
    ans += max(both - 1, 0)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

N = int(input().split()[0])
s_list = []
a_list = []
b_list = []
ab_list = []
ab_count = 0
for _ in range(N):
    s = input()
    s_list.append(s)
    ab_count += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        ab_list.append(s)
    elif s[0] == "B":
        b_list.append(s)
    elif s[-1] == "A":
        a_list.append(s)

if a_list:
    if ab_list:
        a_list.pop()
        ab_count += len(ab_list)
        if b_list:
            ab_count += 1
            b_list.pop()
        ab_count += max(min(len(a_list), len(b_list)), 0)
    else:
        ab_count += min(len(a_list), len(b_list))
elif b_list:
    ab_count += len(ab_list)
else:
    ab_count += max(len(ab_list) - 1, 0)

ans = ab_count
print(ans)

Submission status: Accepted

Solution code:
N=int(input())

ba=0
_a=0
b_=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[-1]=="A":
        _a+=1
    elif s[0]=="B":
        b_+=1

#print(ans)

if ba>0:
    ans+=(ba-1)
    if _a>0:
        _a-=1
        ans+=1
    if b_>0:
        b_-=1
        ans+=1

ans+=min(_a,b_)

print(ans)

Submission status: Accepted

Solution code:
import sys,os
from collections import defaultdict, deque
from math import ceil, floor
if sys.version_info[1] >= 5:
    from math import gcd
else:
    from fractions import gcd
sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = (lambda *something: print(*something)) if 'TERM_PROGRAM' in os.environ else lambda *x: 0
def main(given=sys.stdin.readline):
    input = lambda: given().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    MOD = 10**9+7

    N = II()
    S = [0]*N
    numAB = 0
    numA = 0
    numB = 0
    ans = 0
    for i in range(N):
        s = input()
        ans += s.count('AB')
        if s[-1] == 'A':
            if s[0] == 'B':
                numAB += 1
            else:
                numA += 1
        elif s[0] == 'B':
            numB += 1



    if numA > 0 and numAB > 0:
        numA -= 1
        numAB += 1
    # elif numA == 0 and numAB > 0:
    #     numAB -= 1
    if numB > 0 and numAB > 0:
        numB -= 1
        numAB += 1
    # elif numB == 0 and numAB > 0:
    #     numAB -= 1
    if numAB > 0:

        ans += numAB -1  + min(numA,numB)
    else:
        ans += min(numA,numB)
    
        
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n = int(input())
    S = list(input() for _ in range(n))

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

    if cnt_A + cnt_B > 0:
        print(res + cnt_AB + min(cnt_A, cnt_B))
    else:
        print(res + max(0, cnt_AB - 1))


if __name__ == '__main__':
    resolve()

Submission status: Accepted

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

if a+b>0:
    print(ans+min(a,b)+ab)
else:
    print(ans+max(0,ab-1))

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline


def solve():
    N = int(rl())
    s = [input() for _ in range(N)]
    
    ans = 0
    cnt_a, cnt_b, cnt_ab = 0, 0, 0
    for si in s:
        ans += si.count('AB')
        if si[-1] == 'A' and si[0] == 'B':
            cnt_ab += 1
        elif si[-1] == 'A':
            cnt_a += 1
        elif si[0] == 'B':
            cnt_b += 1
    
    if cnt_ab == 0:
        ans += min(cnt_a, cnt_b)
    else:
        if 0 < cnt_a + cnt_b:
            ans += cnt_ab + min(cnt_a, cnt_b)
        else:
            ans += cnt_ab - 1
    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import math  # noqa
import bisect  # noqa
import queue  # noqa


if __name__ == '__main__':
    N = int(input())
    S = [input() for _ in range(N)]

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

    if cnt_ba > 1:
        cnt += cnt_ba - 1
        cnt_ba = 1
    if (cnt_xa > 0 or cnt_bx > 0) and cnt_ba == 1:
        cnt += 1
    cnt += min(cnt_xa, cnt_bx)

    print(cnt)

Submission status: Accepted

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

for i in range(n):
    s[i] = input()
comb = [[0]*2 for i in range(2)]
    
al = 0
be = 0
ans = 0
for i in range(n):
    m = len(s[i])
    for j in range(m-1):
        if s[i][j] == "A" and s[i][j+1] == "B":
            ans += 1
    if s[i][0] == "B" and s[i][-1] == "A":
        comb[1][1] += 1
    elif s[i][0] == "B" and s[i][-1] != "A":
        comb[0][1] += 1
    elif s[i][0] != "B" and s[i][-1] == "A":
        comb[1][0] += 1
    else:
        comb[0][0] += 1
        
if comb[0][1] == 0 and comb[1][0] == 0:
    ans += max(0,comb[1][1] - 1)
elif comb[0][1] != 0 and comb[1][0] == 0:
    ans += comb[1][1]
elif comb[0][1] == 0 and comb[1][0] != 0:
    ans += comb[1][1]
else:
    ans += (comb[1][1] + 1 + min(comb[1][0]-1,comb[0][1]-1))
    
print(ans)

Submission status: Accepted

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

for i in range(n):
    s[i] = input()
comb = [[0]*2 for i in range(2)]
    
al = 0
be = 0
ans = 0
for i in range(n):
    m = len(s[i])
    for j in range(m-1):
        if s[i][j] == "A" and s[i][j+1] == "B":
            ans += 1
    if s[i][0] == "B" and s[i][-1] == "A":
        comb[1][1] += 1
    elif s[i][0] == "B" and s[i][-1] != "A":
        comb[0][1] += 1
    elif s[i][0] != "B" and s[i][-1] == "A":
        comb[1][0] += 1
    else:
        comb[0][0] += 1
        
if comb[0][1] == 0 and comb[1][0] == 0:
    ans += max(0,comb[1][1] - 1)
elif comb[0][1] != 0 and comb[1][0] == 0:
    ans += comb[1][1]
elif comb[0][1] == 0 and comb[1][0] != 0:
    ans += comb[1][1]
else:
    ans += (comb[1][1] + 1 + min(comb[1][0]-1,comb[0][1]-1))
    
print(ans)

Submission status: Accepted

Solution code:
N,*L = open(0).read().split()

ans = 0
a = 0
b = 0
c = 0
for s in L:
  for j in range(len(s)-1):
    if s[j]=='A' and s[j+1]=='B':
      ans += 1
  if s[-1]=='A' and s[0]=='B':
    c += 1
  elif s[-1]=='A':
    a += 1
  elif s[0]=='B':
    b += 1
if c!=0:
  if a+b>0:
    ans += c+min(a,b)
  else:
    ans += c-1
else:
  ans += min(a,b)
print(ans)

Submission status: Accepted

Solution code:

N = int(input())
xa= 0
bx= 0
ba = 0
ans = 0
for i in range(N):
    s = input()
    ans += s.count("AB") # くっつけなくても見つかるABのカウント
    if s[-1] == "A" and s[0] == "B":
        ba += 1
    elif s[-1] == "A":
        xa+= 1
    elif s[0] == "B":
        bx+= 1

hoge  = "X"
PHASEA = 0
PHASEB = 1
phase  = 0
while ba != 0 or xa != 0 or bx != 0:
    if hoge[-1] == "X":
        if xa > 0:
            xa  -= 1
            hoge += "XA"
        elif ba > 0 :
            ba -= 1
            hoge += "BA"
        else:
            bx -= 1
            hoge += "BX"
    elif hoge[-1] == "A":
        if ba > 0 :
            ba -= 1
            hoge += "BA"
        elif bx > 0:
            bx  -= 1
            hoge += "BX"
        elif xa > 0:
            xa  -= 1
            hoge += "XA"

print(hoge.count("AB") + ans)

Submission status: Accepted

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

if k == a and k == b and k == ab:
  k -= 1
if k == n:
  k -= 1
if k < 0:
  k = 0
ans += k
print(ans)

Submission status: Accepted

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

ab = 0
lastA = 0
onlylastA = 0
firstB = 0
onlyfirstB = 0
for s in S:
    ab += s.count('AB')
    if s[-1] == 'A' and s[0] != 'B':
        lastA += 1
        onlylastA += 1
    if s[0] == 'B' and s[-1] != 'A':
        firstB += 1
        onlyfirstB += 1
    if s[-1] == 'A' and s[0] == 'B':
        lastA += 1
        firstB += 1

ans = ab + min(lastA,firstB)
if lastA != 0 and onlylastA == 0 and onlyfirstB == 0:
    ans = max(ans-1,0)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
s = [(input()) for _ in range(N)]
ans = 0
a_cnt = 0
b_cnt = 0
ab_cnt = 0
for i in range(N):
  if s[i][0] == 'B' and s[i][-1] == 'A':
    ab_cnt += 1
  elif s[i][0] == 'B':
    b_cnt += 1
  elif s[i][-1] == 'A':
    a_cnt += 1
  for j in range(len(s[i])-1):
    if s[i][j] + s[i][j+1] == 'AB':
      ans += 1
if ab_cnt == 0:
  print(ans + min(a_cnt, b_cnt))
else:
  ans += ab_cnt - 1 
  if a_cnt > 0:
    ans += 1
    a_cnt -= 1
  if b_cnt > 0:
    ans += 1
    b_cnt -= 1
  ans += min(a_cnt, b_cnt)
  print(ans)

Submission status: Accepted

Solution code:
# 1: O(N*digit(A))
if False:
    B=[int(i) for i in input().split()]
    N=int(input())
    rep={}
    for i,b in enumerate(B):
        rep[str(b)]=str(i)
    # print(rep)
    ans=[]
    for _ in range(N):
        a=input()
        num=''
        for d in a:
            num+=rep[d]
        ans.append((a,int(num)))
    ans.sort(key=lambda x: x[1])
    for i in range(N): print(ans[i][0])

# 2: 366**2
if False:
    N=int(input())
    S=[tuple(map(int,input().split('/'))) for _ in range(N)]
    if len(S)>=366: print(366)
    elif N==0: print(2)
    else:
        cal=[[] for m in range(12)]
        day=6 #0-6: 0-MON
        for m in range(12):
            if m+1==2: e=29
            elif m+1 in (4,6,9,11): e=30
            else: e=31
            for d in range(1,e+1):
                cal[m].append([d,day,day in (5,6)])
                day=(day+1)%7
        for m,d in S:
            m-=1
            d-=1
            while cal[m][d][2]:
                if d+1<len(cal[m]): d+=1
                else:
                    m+=1
                    m%=12
                    d=0
                if (m,d)==(11,30): break
            cal[m][d][2]=True
        ans=-1
        cnt=0
        for m in range(12):
            for d in range(len(cal[m])):
                if cal[m][d][2]:
                    cnt+=1
                else:
                    ans=max(ans,cnt)
                    cnt=0
        ans=max(ans,cnt)
        print(ans)
        # print(cal[11])

#ARC036-B
if False:
    N=int(input())
    H=[int(input()) for _ in range(N)]
    if N==1: print(1); exit()
    ans=0
    cnt=2
    prev=1 if H[0]<H[1] else 0 #1:<,0:>
    for i in range(1,N-1):
        tmp=1 if H[i]<H[i+1] else 0
        if prev<tmp:
            ans=max(ans,cnt)
            cnt=2
        else:
            cnt+=1
        prev=tmp
    ans=max(ans,cnt)
    print(ans)

#D2019PC-C
if True:
    N=int(input())
    S=[input() for _ in range(N)]
    ans=0
    cnt={'BA':0,'BX':0,'XA':0}
    for s in S: ans+=s.count('AB')
    for s in S:
        l=s[0]
        r=s[-1]
        if l=='B' and r=='A': cnt[l+r]+=1
        elif l=='B': cnt[l+'X']+=1
        elif r=='A': cnt['X'+r]+=1 
    if cnt['BA']:
        ans+=cnt['BA']-1
        if cnt['BX'] and cnt['XA']:
            ans+=min(cnt['BX']-1,cnt['XA']-1)+2
        else:
            ans+=int(bool(cnt['BX']))+int(bool(cnt['XA']))
    else:
        ans+=min(cnt['BX'],cnt['XA'])
    print(ans)

Submission status: Accepted

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

in_str = 0
BX = 0
XA = 0
BA = 0
for str in s:
    in_str += str.count('AB')
    if str[0] == 'B' and str[-1] != 'A':
        BX += 1
    elif str[0] != 'B' and str[-1] == 'A':
        XA += 1
    elif str[0] == 'B' and str[-1] == 'A':
        BA += 1

ans = in_str
if min(XA, BX) >= 1:
    ans += BA + min(XA, BX)
elif max(BX, XA) == 0:
    ans += max(0, BA - 1)
else:
    ans += 1 + BA - 1
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
a_num=0
b_num=0
set_num=0
ans=0
for i in range(n):
    s=list(input())
    for j in range(len(s)-1):
        if s[j]+s[j+1]=="AB":
            ans+=1
    if s[0]=="B" and s[-1]=="A":
        set_num+=1
    elif s[0]=="B":
        b_num+=1
    elif s[-1]=="A":
        a_num+=1
if set_num==0:
    print(ans+min(a_num,b_num))
else:
    ans+=set_num-1
    if not(a_num==0 and b_num==0):
        a_num+=1
        b_num+=1
    print(ans+min(a_num,b_num))

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for _ in range(N)]
res = 0
a = 0
b = 0
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
    for i in range(len(s)-1):
        if s[i] == "A" and s[i+1] == "B":
            res += 1
if a == 0 and b == 0:
    res += max(ba - 1, 0)
elif a == N and b == N:
    res += N-1 + ba
else:
    res += min(a, b) + ba
print(res)

Submission status: Accepted

Solution code:
N=int(input())
A=0
B=0
C=0
ans=0
for _ in range(0,N):
    s=input()
    if s[0]=='B':
        B+=1
    if s[-1]=='A':
        A+=1
    if s[-1]=='A' and s[0]=='B':
        C+=1

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

if A!=C or B!=C:
    print(ans+min(A,B))
else:
    if A==0:
        print(ans)
    else:
        print(ans+C-1)

Submission status: Accepted

Solution code:
import sys
N = int(sys.stdin.readline())
ss = []
for i in range(N):
    ss.append(sys.stdin.readline().rstrip())

incount = 0
has_ba = 0
has_b = 0
has_a = 0
for s in ss:
    incount += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        has_ba += 1
    elif s[0] == 'B':
        has_b += 1
    elif s[-1] == 'A':
        has_a += 1

res = incount
if has_a:
    res += has_ba
elif has_ba:
    has_a += 1
    has_ba -= 1
    res += has_ba
res += min(has_a, has_b)




# if has_ba:
#     res += has_ba - 1
#     has_ba = 1
# if has_b or has_a:
#     npair = min(has_b, has_a)
#     res += npair
#     has_b -= npair
#     has_a -= npair
# if has_ba and (has_b or has_a):
#     res += 1

print(res)

Submission status: Accepted

Solution code:
n=int(input())
s=[ str(input()) for _ in range(n)]
ans=0
a=0
b=0
ab=0
for i in range(n):
    for j in range(len(s[i])-1):
        if s[i][j:j+2]=="AB":
            ans+=1
#print(ans)
for i in range(n):
    if s[i][0]=="B" and s[i][-1]=="A":
        ab+=1
    elif s[i][0]=="B":
        b+=1
    elif s[i][-1]=="A":
        a+=1

ma=max(a,b)
mi=min(a,b)
if 1<=a :
    ans+=ab
else:
    if 1<=ab:
        a+=1
        ab-=1
        ans+=ab

ans+=min(a,b)

#print(a,b,ab)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
def ii(): return int(sys.stdin.readline())

N = ii()
S = [sys.stdin.readline().rstrip() for _ in range(N)]
ans = 0
count = [0, 0, 0]
for s in S:
    ans += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        count[0] += 1
    elif s[0] == "B":
        count[1] += 1
    elif s[-1] == "A":
        count[2] += 1
if count[0]:
    ans += count[0] - 1
    if count[1]:
        ans += 1
        count[1] -= 1
    if count[2]:
        ans += 1
        count[2] -= 1
ans += min(count[1:])
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
count=0
LastA=0
FirstB=0
LA=0
for i in range(0,N):
    f=input()
    count=count+f.count('AB')
    if f[0]=='B' and f[-1]=='A':
        LA=LA+1
    elif f[0]=='B':
        FirstB=FirstB+1
    elif f[-1]=='A':
        LastA=LastA+1
count=count+LA
if LastA==0 and FirstB==0 and LA!=0:
    count=count-1
elif FirstB>=LastA:
    count=count+LastA
else:
    count=count+FirstB
print(count)

Submission status: Accepted

Solution code:
n = int(input())
s= [input() for i in range(n)]
ans1=0
firstB=0
lastA=0
m=n
for i in s:
    ans1+=i.count("AB")
    if i[0]=="B":
        firstB+=1
    if i[-1]=="A":
        lastA+=1
    if i[0]!="B" and i[-1]!="A":
        m-=1
if min(firstB,lastA)==m:
    if m==0:
        print(ans1)
    else:
        print(ans1+m-1)
else:
    print(ans1+min(firstB,lastA))

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
c_1 = 0
c_2 = 0
c_3 = 0
for _ in range(n):
    tmp = input()
    for i in range(len(tmp)-1):
        if tmp[i:i+2] ==  'AB':
            ans += 1
    if tmp[0] == 'B' and tmp[-1] == 'A':
        c_1 += 1
    elif tmp[0] == 'B':
        c_2 += 1
    elif tmp[-1] == 'A':
        c_3 += 1
if c_1 == 0:
    ans += min(c_2,c_3)
else:
    if c_2 + c_3 > 0:
        ans += c_1 + min(c_2,c_3)
    else:
        ans += c_1 - 1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
s = [0]* N
Middle = 0
Bcount = 0
Acount = 0
ABcount = 0
ans = 0
for i in range(N):
    s[i] = input()
    if s[i][0] == "B" and s[i][-1] == "A":
        ABcount += 1
    elif s[i][0] == "B":
        Bcount += 1
    elif s[i][-1] == "A":
        Acount += 1
    for j in range(len(s[i])-1):
        if s[i][j] == "A" and s[i][j+1] == "B":
            Middle += 1
if ABcount==0 and Acount==0 and Bcount==0:
    ans = Middle
elif Acount == 0 and Bcount==0:
    ans = Middle + ABcount - 1
elif Acount == 0:
    ans = Middle + ABcount
elif Bcount == 0:
    ans = Middle + ABcount
else:
    ans = Middle + ABcount +1 + min(Acount-1,Bcount-1)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
ans = 0
f = False
xx = 0
xA = 0
Bx = 0
BA = 0
A = 0
B = 0
for i in range(N):
  S = input()
  for i in range(len(S) - 1):
    if S[i] == "A" and S[i + 1] == "B":
      ans += 1
  if S[0] == "B":
    if S[-1] == "A":BA += 1
    else:Bx += 1
  else:
    if S[-1] == "A":xA += 1
if xA != 0 and Bx != 0:
  ans += BA + 1
  xA -= 1
  Bx -= 1
elif xA != 0:
  ans += BA
  xA -= 1
elif Bx != 0:
  ans += BA
  Bx -= 1
else:
  if BA >= 2:
    ans += BA - 1
ans += min(Bx,xA)
print(ans)

Submission status: Accepted

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

ans = 0
a = 0
b = 0
c = 0
for i in range(n):
    for j in range(len(S[i]) - 1):
        if S[i][j:j+2] == "AB":
            ans += 1
    if S[i][-1] == "A":
        a += 1
    if S[i][0] == "B":
        b += 1
    if S[i][-1] == "A" and S[i][0] == "B":
        c += 1
# print(ans)
ans += min(a, b)
if a == c and a == b and a > 0:
    ans -= 1

print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right

# greedyっぽいなぁ
# ABとなる部分を最大化したい
# *B → A*はむだ、*A→B*となる文字列はそのように連結させたほうがよい
# つまり新たにAB文字列になるのはmin(*Aの数,B*の数)
# ただしB*Aを満たす文字列に関してはどちらにもなりうるので、好きにpaddingできる

N = int(input())
cnt = end_A = start_B = both = 0
for _ in ra(N):
    s = input()
    cnt += s.count('AB')

    if s.endswith('A') and s.startswith('B'):
        both += 1
    elif s.endswith('A'):
        end_A += 1
    elif s.startswith('B'):
        start_B += 1


# 処理の順番も大事
# bothから考えると、bothは基本的にboth−1個のABをつくり,B*Aの文字列に化ける
# つぎにend_Aやstart_Bについて考える。これらによってmin(end_A,start_B)個できる。しかし、B*Aが存在する場合はこれを途中に挟まなければ最大値にならない。
# つまり以下のように処理すれば良い。
# both=0の場合→min(end_A,start_B)
# both>0の場合→ end_A=endB=0→both-1, end_A or endB=0→both, それ以外→both+min(end_A,start_B)
# ∵まずmin(end_A,start_B)個の組をつくりそのうちの一つをばらしてB*Aを挿入するのが最適、min()-1(ばらした分)+2(増える分)+both-1(B*Aの中の'AB'の数)だから


add = min(start_B, end_A)
if both > 0:
    if end_A == 0 and start_B == 0:
        add += both - 1
    else:
        add += both

# print(cnt, add)
print(cnt + add)

Submission status: Accepted

Solution code:
def count_AB(s):
    res = 0
    for j in range(len(s) - 1):
        if s[j] == 'A' and s[j + 1] == 'B':
            res += 1
    return res


N = int(input())
sA, BsA, Bs = (0, 0, 0)
ans = 0
for i in range(N):
    s = input()
    if s[0] == 'B' and s[-1] == 'A':
        BsA += 1
        if len(s[1:-1]) > 0:
            ans += count_AB(s[1:-1])
    elif s[0] == 'B':
        Bs += 1
        if len(s[1:]) > 0:
            ans += count_AB(s[1:])
    elif s[-1] == 'A':
        sA += 1
        if len(s[:-1]) > 0:
            ans += count_AB(s[:-1])
    else:
        ans += count_AB(s)

if BsA == 0:
    ans += min(sA, Bs)
else:
    if sA + Bs == 0:
        ans += BsA - 1
    else:
        ans += BsA
        ans += min(sA, Bs)

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = []
g1 = []
g2 = []
g3 = []

ans = 0
for _ in range(N):
    s = input()
    ans += s.count("AB")
    if s[0] == 'B' and s[-1] == 'A':
        g1.append(s)
    if s[0] == 'B' and s[-1] != 'A':
        g2.append(s)
    if s[0] != 'B' and s[-1] == 'A':
        g3.append(s)


# g1が存在しない = B* と *A の組を作る
if len(g1) == 0:
    ans += min(len(g2), len(g3))
    print(ans)

# B*A が存在する場合
else:
    if len(g2) + len(g3) == 0:
        # B*A しか存在しない場合，これをくっつける
        ans += len(g1) - 1
    else:
        # B*A がlen(g1)個
        # B*  がlen(g2)個
        # *A  がlen(g3)個 ある
        # -> *A B*A B* の形を作れるだけ作る
        ans += len(g1) + min(len(g2), len(g3))
        pass
    print(ans)

Submission status: Accepted

Solution code:
N=int(input())
s=[input() for _ in range(N)]
abcount=0
righta=0
leftb=0
bothab=0
buf=""
for i in range(N):
    buf=s[i]
    l=len(buf)
    if (buf[0]=="B")and(buf[l-1]=="A"):
        bothab=bothab+1
    elif (buf[0]=="B"):
        leftb=leftb+1
    elif (buf[l-1]=="A"):
        righta=righta+1
    for j in range(l-1):
        if (buf[j]=="A")and(buf[j+1]=="B"):
            abcount=abcount+1
abcount=abcount+max(0,bothab-1)
#print(bothab,righta,leftb,abcount)
if (righta>0)and(bothab>0):
    abcount=abcount+1
    righta=righta-1
if (leftb>0)and(bothab>0):
    abcount=abcount+1
    leftb=leftb-1
abcount=abcount+min(righta,leftb)

'''
abcount=abcount+min(bothab,righta,leftb)*2


if min(bothab,righta,leftb)==bothab:
    leftb=leftb-bothab
    righta=righta-bothab
    abcount=abcount+min(leftb,righta)
elif min(bothab,righta,leftb)==righta:
    bothab=bothab-righta
    leftb=leftb-righta
    abcount=abcount+max(0,bothab-1)
    if leftb>0:
        abcount=abcount+1
else:
    bothab=bothab-leftb
    righta=righta-leftb
    abcount=abcount+max(0,bothab-1)
    if righta>0:
        abcount=abcount+1
'''
print(abcount)

Submission status: Accepted

Solution code:
n = int(input())
s = [input() for _ in range(n)]
ab = 0
ba = 0
last_a = 0
first_b = 0
for i in range(n):
  if s[i][0] == "B" and s[i][-1] == "A":
    ba += 1
  elif s[i][-1] == "A":
    last_a += 1
  elif s[i][0] == "B":
    first_b += 1
  ab += s[i].count("AB")
if last_a == 0 and first_b == 0:
  print(ab+ba-1) if ba != 0 else print(ab)
else:
  print(ab+ba+min(last_a,first_b))

Submission status: Accepted

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

sm=0

for i in range(N):
    count=0
    tmp=-1
    for j in range(len(s[i])):
        if s[i][j]=="A":
            tmp=1
        elif s[i][j]=="B":
            if tmp==1:
                count+=1
            tmp=-1
        else:
            tmp=-1
    sm+=count
chk=[0 for _ in range(N)]
for i in range(N):
    if s[i][0]=="B" and s[i][-1]=="A":
        chk[i]=3
    elif s[i][-1]=="A":
        chk[i]=2
    elif s[i][0]=="B":
        chk[i]=1
x=0
y=0
z=0
#print(sm)
ans=sm
for i in range(N):
    if chk[i]==3:
        z+=1
    if chk[i]==2:
        x+=1
    if chk[i]==1:
        y+=1
if z>0:
    a=z-1
    ans+=a
    if x>0:
        ans+=1
        x-=1
    if y>0:
        ans+=1
        y-=1
ans+=min(x,y)
print(ans)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

n = int(readline())
cnt_a = 0
cnt_b = 0
cnt_c = 0
cnt = 0
for i in range(n):
    s = input()
    for j in range(1, len(s)):
        if s[j - 1] == 'A' and s[j] == 'B':
            cnt += 1
    if s[0] == 'B' and s[-1] == 'A':
        cnt_c += 1
    elif s[0] == 'B':
        cnt_b += 1
    elif s[-1] == 'A':
        cnt_a += 1
ans = cnt
if cnt_c == 0:
    ans += min(cnt_a, cnt_b)
else:
    if cnt_a + cnt_b > 0:
        ans += cnt_c + min(cnt_a, cnt_b)
    else:
        ans += cnt_c - 1
print(ans)