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

ans = 0
ab = 0
tail_a = 0
head_b = 0

for _ in range(N):
    s = input()
    ans += s.count('AB')

    if s[-1] == 'A' and s[0] == 'B':
        ab += 1
    elif s[-1] == 'A' and s[0] != 'B':
        tail_a += 1
    elif s[-1] != 'A' and s[0] == 'B':
        head_b += 1

if ab == 0:
    print(ans+min(tail_a, head_b))
elif ab > 0 and max(tail_a, head_b) > 0:
    print(ans+ab+min(tail_a, head_b))
elif max(tail_a, head_b) == 0:
    print(ans+ab-1)

Submission status: Accepted

Solution code:
n = int(input())
last_a_cnt = 0
top_b_cnt = 0
last_a_top_b_cnt = 0
ab_cnt = 0

for _ in range(n):
    s = input()
    ab_cnt += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A': last_a_top_b_cnt += 1
    elif s[0] == 'B' and s[-1] != 'A': top_b_cnt += 1
    elif s[0] != 'B' and s[-1] == 'A': last_a_cnt += 1


if last_a_cnt > 0:
    ans = 0
    last_a_cnt -= 1
    ans += last_a_top_b_cnt    
    ans += min(last_a_cnt+1, top_b_cnt)
    ans += ab_cnt

else:
    ans = 0
    if last_a_top_b_cnt > 0:
        ans += (last_a_top_b_cnt-1)
        ans += min(1, top_b_cnt)
    ans += ab_cnt

print(ans)

Submission status: Accepted

Solution code:
import sys
import math
import copy
import heapq
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
sys.setrecursionlimit(1000000)

# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = float("inf")
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)

def nck(n, k, kaijyo):
    return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD

def npk(n, k, kaijyo):
    if k == 0 or k == n:
        return n % MOD
    return (kaijyo[n] * divide(kaijyo[n-k])) % MOD

def fact_and_inv(SIZE):
    inv = [0] * SIZE  # inv[j] = j^{-1} mod MOD
    fac = [0] * SIZE  # fac[j] = j! mod MOD
    finv = [0] * SIZE  # finv[j] = (j!)^{-1} mod MOD
    inv[1] = 1
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    for i in range(2, SIZE):
        inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD
        fac[i] = fac[i - 1] * i % MOD
        finv[i] = finv[i - 1] * inv[i] % MOD

    return fac, finv

def renritsu(A, Y):
    # example 2x + y = 3, x + 3y = 4
    # A = [[2,1], [1,3]])
    # Y = [[3],[4]] または [3,4]
    A = np.matrix(A)
    Y = np.matrix(Y)
    Y = np.reshape(Y, (-1, 1))
    X = np.linalg.solve(A, Y)

    # [1.0, 1.0]
    return X.flatten().tolist()[0]

class TwoDimGrid:
    # 2次元座標 -> 1次元
    def __init__(self, h, w, wall="#"):
        self.h = h
        self.w = w
        self.size = (h+2) * (w+2)
        self.wall = wall
        self.get_grid()
        # self.init_cost()

    def get_grid(self):
        grid = [self.wall * (self.w + 2)]
        for i in range(self.h):
            grid.append(self.wall + getS() + self.wall)

        grid.append(self.wall * (self.w + 2))
        self.grid = grid
    def init_cost(self):
        self.cost = [INF] * self.size

    def pos(self, x, y):
        # 壁も含めて0-indexed 元々の座標だけ考えると1-indexed
        return y * (self.w + 2) + x
    def getgrid(self, x, y):
        return self.grid[y][x]
    def get(self, x, y):
        return self.cost[self.pos(x, y)]
    def set(self, x, y, v):
        self.cost[self.pos(x, y)] = v
        return
    def show(self):
        for i in range(self.h+2):
            print(self.cost[(self.w + 2) * i:(self.w + 2) * (i+1)])
    def showsome(self, tgt):
        for t in tgt:
            print(t)
        return
    def showsomejoin(self, tgt):
        for t in tgt:
            print("".join(t))
        return

    def search(self):
        grid = self.grid
        move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        move_eight = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
        # for i in range(1, self.h+1):
        #     for j in range(1, self.w+1):
        #         cx, cy = j, i
        #         for dx, dy in move_eight:
        #             nx, ny = dx + cx, dy + cy


def soinsu(n):
    ret = defaultdict(int)
    for i in range(2, int(math.sqrt(n) + 2)):
        if n % i == 0:
            while True:
                if n % i == 0:
                    ret[i] += 1
                    n //= i
                else:
                    break

    if not ret:
        return {n: 1}
    return ret


def solve():
    n = getN()
    ans, a, b = 0,0,0
    andb = 0
    for i in range(n):
        prev = ""
        S = getS()
        for c in S:
            if prev == "A" and c == "B":
                ans += 1

            prev = c
        if S.startswith("B"):
            b += 1
        if S.endswith("A"):
            a += 1
        if S.startswith("B") + S.endswith("A"):
            andb  += 1

    if a == b and b == andb and b > 0:
        b -= 1

    print(ans + min(a, b))



def main():
    n = getN()
    for _ in range(n):
        solve()

    return
if __name__ == "__main__":
    # main()
    solve()

Submission status: Accepted

Solution code:
n = int(input())
cnt_a = cnt_b = cnt_ba = 0
ans = 0
for _ in range(n):
    s = input()
    ans += s.count('AB')
    if s[0] == 'B':
        cnt_b += 1
        if s[-1] == 'A':
            cnt_ba += 1
    if s[-1] == 'A':
        cnt_a += 1

# print(ans, cnt_a, cnt_b)
if cnt_a == cnt_b == n:
    ans += n - 1
elif cnt_ba > 0 and cnt_a == cnt_b == cnt_ba:
    ans += cnt_ba - 1
else:
    ans += min(cnt_a, cnt_b)
print(ans)

Submission status: Accepted

Solution code:
N=int(input())

answer=0
num_ba=0
num_a=0
num_b=0
for _ in range(N):
  s=input()
  for i in range(1,len(s)):
    if s[i-1]=="A" and s[i]=="B":
      answer+=1
  
  if s[0]=="B" and s[-1]=="A":
    num_ba+=1
  elif s[0]=="B":
    num_b+=1
  elif s[-1]=="A":
    num_a+=1

if num_ba>0:
  answer+=num_ba-1
  if num_b>0:
    answer+=1
    num_b-=1
  if num_a>0:
    answer+=1
    num_a-=1
  
answer+=min(num_a,num_b)
print(answer)

Submission status: Accepted

Solution code:
a=b=c=ans=0
for _ in range(int(input())):
    s=input()
    ans+=s.count("AB")
    a+=s[-1]=="A"
    b+=s[0]=="B"
    c+=s[-1]+s[0]=="AB"
print(ans+min(a,b)-(0<a==b==c))

Submission status: Accepted

Solution code:
a = b = c = ans = 0
for _ in range(int(input())):
    s = input()
    ans += s.count("AB")
    a += s[-1] == "A"
    b += s[0] == "B"
    c += s[-1] + s[0] == "AB"
print(ans+min(a, b)-(0 < a == b == c))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
n = int(input())
a = b = c = ans = 0
for _ in range(n):
    s = input()
    ans += s.count("AB")
    a += s[-1] == "A"
    b += s[0] == "B"
    c += s[-1] + s[0] == "AB"
print(ans + min(a, b) - (0 < a == b == c))

Submission status: Accepted

Solution code:
n = int(input())
internal_AB = 0
B_A = 0
B_ = 0
_A = 0
for i in range(n):
    s = input()
    for j in range(len(s)-1):
        if s[j] == 'A' and s[j+1] == 'B':
            internal_AB += 1
    if s[0] == 'B' and s[-1] == 'A':
        B_A += 1
    elif s[0] == 'B':
        B_ += 1
    elif s[-1] == 'A':
        _A += 1
if _A == 0 and B_ == 0:
    ans = max(0,B_A - 1)
elif _A == 0 or B_ == 0:
    ans = B_A
else:
    if B_A > 0:
        ans = B_A +1 + min(_A-1,B_-1)
    else:
        ans = min(B_,_A)
print(ans + internal_AB)

Submission status: Accepted

Solution code:
N = int(input())
ans,a,b,ab = 0,0,0,0

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

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

Submission status: Accepted

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

# In[13]:


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


# In[14]:


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


# In[ ]:

Submission status: Accepted

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
#from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque

INF = 1 << 50



def run():
    N = int(input())
    S = [input() for _ in range(N)]
    countA = 0
    countB = 0
    countBA = 0
    countAB = 0
    for s in S:
        countAB += s.count('AB')
        #print(s, s.count('AB'))
        if s[0] == 'B':
            if  s[-1] == 'A':
                countBA += 1
            else:
                countB += 1
        elif s[-1] == 'A':
            countA += 1

    #print(countA, countB, countBA, countAB)
    if countBA > 1:
        countAB += countBA - 1
        countBA = 0

        if countA > 0:
            countAB += 1
            countA -= 1
        if countB>0:
            countAB += 1
            countB -= 1

    plus = min(countA, countB)

    countAB += plus
    countA -= plus
    countB -= plus

    plus = min(countBA, countA)
    countAB += plus
    countBA -= plus
    countA -= plus

    plus = min(countBA, countB)
    countAB += plus

    print(countAB)






if __name__ == "__main__":
    run()

Submission status: Accepted

Solution code:
def resolve():
    '''
    code here
    '''
    N = int(input())
    Ss = [input() for _ in range(N)]

    num_ab = 0
    num_a = 0
    num_b = 0
    num_b_a = 0

    for line in Ss:

        num_ab += line.count('AB')
        if line[0] == 'B' and line[-1] == 'A':
            num_b_a += 1
        elif line[-1] == 'A':
            num_a += 1
        elif line[0] == 'B':
            num_b += 1
        
    res = num_ab
    if num_b_a > 0:
        res += num_b_a -1

        if num_a > 0:
            res += 1
            num_a -= 1

        if num_b > 0:
            res += 1
            num_b -= 1

    res += min(num_a, num_b)
    print(res)


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
N = int(input())
ab, a, b, ans = 0, 0, 0, 0
for i in range(N):
  s = str(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
    
if ab > 0:
  ans += ab - 1
  if a > 0:
    ans += 1
    a -= 1
  if b > 0:
    ans += 1
    b -= 1
ans += min(a, b)
print(ans)

Submission status: Accepted

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

cnt = 0
cnta = 0
cntb = 0
cntab = 0
for i in range(n):
    if 'AB' in s[i]:
        cnt += s[i].count('AB')
    if s[i][0] == 'B' and s[i][-1] == 'A':
        cntab += 1
    elif s[i][0] == 'B':
        cntb += 1
    elif s[i][-1] == 'A':
        cnta += 1
    
if cntab == 0:
    cnt += min(cnta, cntb)
else:
    if cnta + cntb > 0:
        cnt += cntab + min(cnta, cntb)
    else:
        cnt += cntab - 1
print(cnt)

Submission status: Accepted

Solution code:
#-----------------------------
#https://atcoder.jp/contests/agc008/submissions/15248942
import sys
 
sys.setrecursionlimit(10 ** 8)
ini = lambda: int(sys.stdin.readline())
inm = lambda: map(int, sys.stdin.readline().split())
inl = lambda: list(inm())
ins = lambda: sys.stdin.readline().rstrip()
debug = lambda *a, **kw: print("\033[33m", *a, "\033[0m", **dict(file=sys.stderr, **kw))
#-----------------------------
N = ini()
ans = 0
lastA = 0
firstB = 0
BA = 0

for i in range(N):
    s = input()
    #siの文字列内のABを抽出
    for j in range(len(s)-1):
        if s[j:j+2] == "AB":
            ans += 1

    #先頭Bかつ末尾A、先頭B、末尾A、を抽出
    if s[0] == "B" and s[-1] == "A":
        BA += 1
    elif s[0] == "B":
        firstB += 1
    elif s[-1] == "A":
        lastA += 1

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

#BAと末尾Aと先頭Bをつなげて、余った末尾Aと先頭Bをつなげる
if BA >= 1 and lastA >= 1 and firstB >=1:
    ans += 2 + min(lastA-1,firstB-1)
#BAと末尾Aをつなげる
elif BA >= 1 and lastA >= 1 and firstB == 0:
    ans += 1
#BAと先頭Bをつなげる
elif BA >= 1 and lastA == 0 and firstB >= 1:
    ans += 1
#末尾Aと先頭Bをつなげる
elif BA < 1 and lastA >= 1 and firstB >= 1:
    ans += min(lastA,firstB)

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
ba = 0 # bで始まりaで終わる
a = 0 # 末尾がa
b = 0 # 先頭がb
sss = []
for i in range(n):
    s = input()
    for j in range(len(s)-1):
        if s[j:j+2] == 'AB':
            ans+=1
    if s[0] == 'B' and s[-1] == 'A': ba += 1
    else:
        if s[0] == 'B': b+=1
        if s[-1] == 'A': a+=1
"""
貪欲で解けると思う
まずbaを並べて、可能な限りその先頭にa、末尾にbをつける
a,bが残るようであれば、ペアにする
"""
if ba > 0:
    ans += ba-1
    if a>0:
        ans+=1
        a-=1
    if b>0:
        ans+=1
        b-=1
ans += min(a, b)
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
# from math import ceil, floor, log2
# from collections import deque
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np    # cumsum
# from bisect import bisect_left, bisect_right

def solve():
    N = II()
    A = []
    B = []
    BA = []
    cnt = 0
    for i in range(N):
        s = input()
        l = list(s)
        if l[0] == 'B' and l[-1] == 'A':
            BA.append(i)
        elif l[0] == 'B':
            B.append(i)
        elif l[-1] == 'A':
            A.append(i)
        cnt += s.count('AB')
    # print(A, B, BA, cnt)
    la = len(A)
    lb = len(B)
    lba = len(BA)

    if la > 0 and lb > 0:
        cnt += min(la, lb) + lba
    elif la == 0 and lb == 0:
        if lba > 1:
            cnt += lba - 1
    else:
        cnt += lba
    print(cnt)


if __name__ == '__main__':
    solve()

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
n=int(input())
a=0
b=0
ab=0
num=0
for i in range(n):
    s=input()
    if s[0]=="B" and s[-1]=="A":
        ab+=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":
            num+=1
if a!=0 and b!=0:
    num+=ab+1
    a-=1
    b-=1
    num+=min(a,b)
elif a!=0:
    num+=ab
elif b!=0:
    num+=ab
else:
    num+=max(0,ab-1)
print(num)

Submission status: Accepted

Solution code:
import sys,math,collections,itertools
input = sys.stdin.readline

N = int(input())
lAend = 0
lBstart = 0
lAe_Bs = 0
cnt = 0

for i in range(N):
    S = input().rstrip()
    if S[0]=='B' and S[-1] =='A':
        lAe_Bs+=1
    elif S[0] == 'B':
        lBstart+=1
    elif S[-1] == 'A':
        lAend+=1
    cnt += S.count('AB')

if lAe_Bs >0:
    cnt += lAe_Bs -1
    
if lAe_Bs > 0 and lAend >0:
    cnt += 1
    lAend -=1
if lAe_Bs > 0 and lBstart>0:
    cnt +=1
    lBstart -=1

cnt += min(lAend,lBstart)

print(cnt)

Submission status: Accepted

Solution code:
import sys,math,collections,itertools
input = sys.stdin.readline

N = int(input())
Aend = []
Bstart = []
Ae_Bs = []
cnt = 0

for i in range(N):
    S = input().rstrip()
    if S[0]=='B' and S[-1] =='A':
        Ae_Bs.append(S)
    elif S[0] == 'B':
        Bstart.append(S)
    elif S[-1] == 'A':
        Aend.append(S)
    cnt += S.count('AB')

lAe_Bs = len(Ae_Bs)
lBstart = len(Bstart)
lAend = len(Aend)

if lAe_Bs >0:
    cnt += lAe_Bs -1
    
if lAe_Bs > 0 and lAend >0:
    cnt += 1
    lAend -=1
if lAe_Bs > 0 and lBstart>0:
    cnt +=1
    lBstart -=1

cnt += min(lAend,lBstart)

print(cnt)

Submission status: Accepted

Solution code:
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    N = I()
    s = [SS() for _ in range(N)]

    ans = sum([i.count('AB') for i in s])

    # .*AとB.*をいくつくっつけられるか
    # .*AにB.*をくっつけた後、間にB.*Aを挟む方針 挟み方はどうでもいい
    tA = 0
    fB = 0
    fBtA = 0
    for i in s:
        if i[-1] == 'A' and i[0] == 'B':
            fBtA += 1
        elif i[-1] == 'A':
            tA += 1
        elif i[0] == 'B':
            fB += 1

    if tA == fB == 0:
        ans += max(fBtA - 1, 0)
    else:
        ans += min(tA, fB) + fBtA

    print(ans)

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
n,*s=open(0).read().split()
w=''
b=[]
a=[]
e=""
for i in s:
    if i[-1]=='A' and i[0]=="B":
        w+=i
    elif i[-1]=='A':
        a.append(i)
    elif i[0]=='B':
        b.append(i)
    else:
        e+=i
#print(w)
a=iter(a)
b=iter(b)
if len(w)!=0:
    w=next(a,'')+w+next(b,'')
i,j=next(a,''),next(b,'')
while i!='' or j!='':
    w+=i+j
    i,j=next(a,''),next(b,'')
w+=e
print(w.count('AB'))

Submission status: Accepted

Solution code:
n = int(input())
s = [input() for _ in range(n)]
count = 0
a_count = 0
b_count = 0
ab_count = 0

for ss in s:
    count += ss.count("AB")
    if ss[0] == "B" and ss[-1] == "A":
        ab_count += 1
    elif ss[0] != "B" and ss[-1] == "A":
        a_count += 1
    elif ss[0] == "B" and ss[-1] != "A":
        b_count += 1

tmp_count = min(a_count,b_count)
if ab_count == 0:
    count += tmp_count
else:
    if a_count + b_count > 0:
        count += ab_count + tmp_count
    else:
        count += ab_count - 1
print(count)

Submission status: Accepted

Solution code:
def main():
    import sys

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

    n = int(input())
    s_table = [0]*3
    ans = 0
    for i in range(n):
        s = input()
        ans += s.count('AB')
        if s[0] == 'B' and s[-1] == 'A':
            s_table[0] += 1
        elif s[0] == 'B' and s[-1] != 'A':
            s_table[1] += 1
        elif s[0] != 'B' and s[-1] == 'A':
            s_table[2] += 1
    
    if s_table[0] == 0:
        ans += min(s_table[1:])
    elif sum(s_table[1:]) > 0:
        ans += s_table[0]+min(s_table[1:])
    else:
        ans += s_table[0]-1
    print(ans)
        
    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())
 
As = 0
Bs = 0
ABs = 0
BAs = 0
 
for i in range (0, N):
	K = str(input())
	ABs+= K.count('AB')
	if K[0] == 'B':
		if K[-1] == 'A':
			BAs+=1
		else:
			Bs+=1
	elif K[-1] == 'A':
		As+=1

if BAs== 0:
	print(ABs+min(As, Bs))
elif As+Bs>0:
	print(ABs+BAs+min(As, Bs))
else:
	print(ABs+BAs-1)

Submission status: Accepted

Solution code:
import sys

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


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

    cnt_BA = cnt_A = cnt_B = cnt_AB = 0
    for _ in range(n):
        s = input().rstrip()
        cnt_AB += s.count("AB")

        if s[0] == "B" and s[-1] == "A":
            cnt_BA += 1
        elif s[0] == "B":
            cnt_B += 1
        elif s[-1] == "A":
            cnt_A += 1

    res = cnt_AB + max(0, (cnt_BA - 1)) + min(cnt_A, cnt_B)
    cnt_BA = 1 if cnt_BA >= 1 else 0
    cnt_A = cnt_A - min(cnt_A, cnt_B)
    cnt_B = cnt_B - min(cnt_A, cnt_B)
    if cnt_A != 0 and cnt_BA != 0:
        res += min(cnt_A, cnt_BA)
    elif cnt_B != 0 and cnt_BA != 0:
        res += min(cnt_B, cnt_BA)
    print(res)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
N = int(input())
cnt = 0
st_cnt = 0
end_cnt =0
same_cnt =0

for k in range(N):
    s = input()
    cnt +=s.count("AB")

    if (s[0] =='B') & (s[-1]=='A'):
        same_cnt += 1
    elif (s[0] =='B'):
        st_cnt +=1
    elif (s[-1] == 'A'):
        end_cnt += 1
if same_cnt==0:
    print(cnt + same_cnt + min(st_cnt, end_cnt))
elif (st_cnt==0) and (end_cnt==0):
    print(cnt+same_cnt-1)
else:print(cnt+same_cnt+min(st_cnt,end_cnt))

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
n=int(input())
c1=0
c2=0
c3=0
ans=0
for i in range(n):
    s=input()
    if s[0]=="B" and s[-1]=="A":
        c1+=1
    if s[0]=="B" and s[-1]!="A":
        c2+=1
    if s[0]!="B" and s[-1]=="A":
        c3+=1
    for j in range(len(s)-1):
        if s[j]=="A"and s[j+1]=="B":
            ans+=1
if c1==0:
    ans+=min(n-1,min(c2,c3))
elif c1!=0:
    if c2+c3>0:
        ans+=c1+min(c2,c3)
    if c2+c3==0:
        ans+=c1-1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
ans = 0
both = 0
start_B = 0
end_A = 0
for _ in range(N):
    s = input()
    ans += s.count("AB")
    isB = s.startswith("B")
    isA = s.endswith("A")
    if isA and isB:
        both += 1
    if isA:
        end_A += 1
    if isB:
        start_B += 1
ans += min(start_B, end_A)
if start_B == both and both == end_A and start_B != 0:
    ans = max(0, ans - 1)
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
ans=0
cnt_a,cnt_b,cnt_c=0,0,0
for i in range(N):
    s=input()
    ans+=s.count("AB")
    s=s.replace("AB","")
    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
if cnt_c==0:
    print(ans+min(cnt_a,cnt_b))
elif cnt_a+cnt_b == 0:
    print(ans+cnt_c-1)
else:
    print(ans+cnt_c+min(cnt_a,cnt_b))

Submission status: Accepted

Solution code:
N = int(input())
S_list = [input() for x in range(N)]
#print(S_list)

# Aで終わる、かつ、Bで始まらない
a_count = 0
# Aで終わらない、かつ、Bで始まる
b_count = 0
# Aで終わる、かつ、Bで始まる
ab_count = 0

for s in S_list:
    if s[0] != "B" and s[-1] == "A":
        a_count += 1
    elif s[0] == "B" and s[-1] != "A":
        b_count += 1
    elif s[0] == "B" and s[-1] == "A":
        ab_count += 1

# 単体で含まれる"AB"の数
temp = sum([x.count("AB") for x in S_list])

if ab_count == 0:
    print(temp + min(a_count, b_count))
else:
    # a_count、b_countともに0の場合
    if a_count == 0 and b_count == 0:
        print(temp + ab_count - 1)

    # a_count または b_count が0でない場合
    else:
        print(temp + min(a_count, b_count) + ab_count)

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
cnt_a, cnt_b, cnt_ab  = 0, 0, 0
for i in range(n):
    s = input()
    ans += s.count("AB")
    if s[-1] == "A":
        cnt_a += 1
    if s[0] == "B":
        cnt_b += 1
    if s[0] == "B" and s[-1] == "A":
        cnt_ab += 1
#print(cnt_a, cnt_b, cnt_ab)
print(ans + min(cnt_a, cnt_b) if cnt_ab < max(cnt_a, cnt_b) or cnt_b == 0 else ans + (cnt_ab - 1))

Submission status: Accepted

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

last_A = []
first_B = []
A_B = []
for i in range(N):
    if (S[i][0] == 'B' and S[i][-1] == 'A'):
        A_B.append(S[i])
    elif (S[i][0] == 'B'):
        first_B.append(S[i])
    elif (S[i][-1] == 'A'):
        last_A.append(S[i])

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


def calc_comb(sb, fa, sbfa):
    if sbfa == 0:
        return min(sb, fa)
    elif sb == 0 and fa == 0:
        return sbfa - 1
    else:
        return sbfa + min(sb, fa)


print(count + calc_comb(len(first_B), len(last_A), len(A_B)))

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for _ in range(N)]
 
# 文字列にABが入ってる数 + 組み合わせて入る数
# 文字列にABが入ってる数 + f(Aで終わる数, Bで始まる数, Bで始まりAで終わる数)
include = 0
sb = 0
fa = 0
sbfa = 0
for s in S:
    include += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        sbfa += 1
    elif s[0] == 'B':
        sb += 1
    elif s[-1] == 'A':
        fa += 1

def calc_comb(sb, fa, sbfa):
    if sbfa == 0:
        return min(sb, fa)
    elif max(sb, fa)==0:
        return sbfa -1
    else:
        return sbfa + min(sb, fa)

print(include + calc_comb(sb, fa, sbfa))

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for _ in range(N)]
 
# 文字列にABが入ってる数 + 組み合わせて入る数
# 文字列にABが入ってる数 + f(Aで終わる数, Bで始まる数, Bで始まりAで終わる数)
sb = 0
fa = 0
sbfa = 0
for s in S:
    if s[0] == 'B' and s[-1] == 'A':
        sbfa += 1
    elif s[0] == 'B':
        sb += 1
    elif s[-1] == 'A':
        fa += 1

include = sum([x.count("AB") for x in S])

def calc_comb(sb, fa, sbfa):
    if sbfa == 0:
        return min(sb, fa)
    elif max(sb, fa)==0:
        return sbfa -1
    else:
        return sbfa + min(sb, fa)

print(include + calc_comb(sb, fa, sbfa))

Submission status: Accepted

Solution code:
n = int(input())
s_array = [input() for x in range(n)]
a_count = 0
b_count = 0
ab_count = 0
for s in s_array:
    if s[-1] == "A" and s[0] != "B":
        a_count += 1
    elif s[0] == "B" and s[-1] != "A":
        b_count += 1
    elif s[0] == "B" and s[-1] == "A":
        ab_count += 1
    else:
        pass

res = sum([x.count("AB") for x in s_array])

if n == 1:
    print(res)
elif ab_count == 0:
    print(res + min(a_count, b_count))
elif a_count == 0 and b_count == 0:
    print(res - 1 + ab_count)
else:
    print(res + min(a_count, b_count) + ab_count)

Submission status: Accepted

Solution code:
n=int(input())
c=0
a=0
b=0
ab=0

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

c+=min(a,b)+ab if max(a,b)!=0 else ab-1 if ab>0 else 0
print(c)

Submission status: Accepted

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

#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

def main():
	n=II()

	a=0
	b=0
	ab=0
	ans=0

	for _ in range(n):
		s=input().rstrip().decode()
		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

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

	print(ans)







if __name__ == "__main__":
	main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())
xa = 0
by = 0
ba = 0
counter = 0
for _ in range(n):
  s = input()
  counter += s.count('AB')
  if s[0]=='B':
    if s[-1]=='A':
      ba += 1
    else:
      by += 1
  elif s[-1] == 'A':
    xa += 1
if ba == 0:
  counter += min(xa,by)
else:
  if xa+by== 0:
    counter += ba -1
  else:
    counter += ba + min(xa,by)
print(counter)

Submission status: Accepted

Solution code:
from math import ceil,floor,comb,factorial,gcd,pow,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from copy import deepcopy
from time import time
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

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

a = 0
b = 0
ab = 0
c = 0
for x in s:
    ab += x.count("AB")
    if x[0] == 'B' and x[-1] == 'A':
        c += 1
    elif x[0] == 'B':
        b += 1
    elif x[-1] == 'A':
        a += 1
    
print( ab + max(c-1, 0) + min(a, b) + (1 if a + b != 0 and c > 0 else 0))

Submission status: Accepted

Solution code:
n = int(input())
hB = set()
tA = set()
cAB = 0
for i in range(n):
    s = input()
    cAB += s.count('AB')
    if s[0] == 'B': hB.add(i)
    if s[-1] == 'A': tA.add(i)
if len(hB&tA)>0:
    if len(hB)-len(hB&tA)>0 or len(tA)-len(hB&tA)>0:
        print(cAB+min(len(hB),len(tA)))
    else:
        print(cAB+min(len(hB),len(tA))-1)
else:
    print(cAB+min(len(hB),len(tA)))

Submission status: Accepted

Solution code:
n, *ss = open(0).read().split()
ans = 0
inter_count = sum([s.count('AB') for s in ss])
ans += inter_count

_a = sum(s[-1] == 'A' for s in ss)
b_ = sum(s[0] == 'B' for s in ss)
b_a = sum(s[0] == 'B' and s[-1] == 'A' for s in ss)
_a -= b_a
b_ -= b_a

ans += max(0,b_a-1)

if b_a:
    ans += bool(b_)
    b_ -= bool(b_)
    ans += bool(_a)
    _a -= bool(_a)

ans += min(b_, _a)
print(ans)