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
N = int(sys.stdin.readline())
S = list(map(str,sys.stdin.read().rstrip().split("\n")))

ans = 0
A = 0
B = 0
BA = 0
for s in S:
	ans += s.count('AB')
	if  s[0] == 'B' and s[-1] == 'A':
		BA += 1
		continue
	elif s[0] == 'B':
		B += 1
	elif s[-1] == 'A':
		A += 1

if BA == 0:
	ans += min(A,B)
else:
	if A+B > 0:
		ans += BA + min(A,B)
	else:
		ans += BA-1

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

n=int(input())
data=[0]*2; f=1
for i in range(n):
    s=input()
    count+=s.count("AB")
    if s[0]=="B" and s[-1]=="A":
        data[0]+=1; data[1]+=1
    elif s[0]=="B":
        data[1]+=1; f=0
    elif s[-1]=="A":      
        data[0]+=1; f=0
count+=max(0,min(data)-f)
print(count)

Submission status: Accepted

Solution code:
n = int(input())
s = [input() for _ in range(n)]
ans = 0
w = 0
a = 0
b = 0

for c in s:
    ans += c.count("AB")
    if c[0] == "B" and c[-1] == "A":
        w += 1
    elif c[0] == "B":
        b += 1
    elif c[-1] == "A":
        a += 1

if a == b == 0:
    w -= 1
ans += max(w,0) + min(a,b)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
 
ABcount = 0
Acount = 0
Bcount = 0
Aset = set()
Bset = set()
for i in range(N):
    s = input()
 
    if s[0] == "B":
        Bcount += 1
        Bset.add(s)
 
    if s[-1] == "A":
        Acount += 1
        Aset.add(s)
    
    buf = ""
    for char in s:
        if buf + char == "AB":
            ABcount += 1
        buf = char

if Acount > Bcount:
    print(ABcount + Bcount)
elif Acount < Bcount:
    print(ABcount + Acount)
else:
    if Aset == Bset and len(Aset) != 0:
        print(ABcount + Acount - 1)
    else:
        print(ABcount + Acount)

Submission status: Accepted

Solution code:
N = int(input())
inner = 0
B_ = 0
_A = 0
BA = 0

for _ in range(N):
    S = input()
    inner += S.count('AB')
    if S[0] == 'B':
        if S[-1] == 'A':
            BA += 1
        else:
            B_ += 1
    elif S[-1] == 'A':
        _A += 1

if BA == 0:
    print(inner + min(B_, _A))
else:
    if B_ == 0 and _A == 0:
        print(inner + BA - 1)
    else:
        print(inner + BA + min(B_, _A))

Submission status: Accepted

Solution code:
from math import ceil
n=int(input())
s=[input() for i in range(n)]
cba=0
ca=0
cb=0
ans=0
for i in range(n):
  if s[i][0]=='B':
    if s[i][len(s[i])-1]=='A':
      cba+=1
    else:
      cb+=1
  if s[i][0]!='B' and s[i][len(s[i])-1]=='A':
    ca+=1
  ans+=s[i].count('AB')
if cba>0:
  ans+=cba-1
  if cb>0 and ca>0:
    ans+=2+min(cb-1,ca-1)
  elif cb==0 and ca==0:
    ans+=0
  else:
    ans+=1
else:
  ans+=min(cb,ca)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from _collections import deque
from _ast import Num


def parser():
    while 1:
        data = list(input().split(' '))
        for number in data:
            if len(number) > 0:
                yield (number)


input_parser = parser()


def gw():
    global input_parser
    return next(input_parser)


def gi():
    data = gw()
    return int(data)


MOD = int(1e9 + 7)

import numpy
from collections import deque
from math import sqrt
from math import floor
# https://atcoder.jp/contests/arc067/tasks/arc067_a
# C - Factors of Factorial
"""
need to consider the case that ticket is not enough to lower everything
"""

N = gi()
ans = 0
cnt = [0] * 3
for i in range(N):
    s = gw()
    if s[0] == 'B':
        if s[-1] == 'A':
            cnt[0] += 1
        else:
            cnt[1] += 1
    elif s[-1] == 'A':
        cnt[2] += 1

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

if cnt[0] == 0:
    ans += min(cnt[1], cnt[2])
elif (cnt[1] + cnt[2]):
    ans += cnt[0] + min(cnt[1], cnt[2])
else:
    ans += cnt[0] - 1
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict, deque
import bisect
from heapq import *
from math import factorial, ceil, floor
from collections import defaultdict
sys.setrecursionlimit(200000)
input = sys.stdin.readline

# N, M, = map(int, input().split())
# N = int(input())
# L = [int(v) for v in input().split()]
# L = [[int(v) for v in input().split()] for _ in range(N)]
# L = [int(input()) for _ in range(N)]
# L = [list(input().strip())  for _ in range(N)]
# S = input().strip()

N, = map(int, input().split())
L = [list(input().strip())  for _ in range(N)]

b = defaultdict(list)
a = defaultdict(list)
c = defaultdict(list)
for v in L:
    if v[0] == "B":
        if v[-1] == "A":
            c[v[0]].append("".join(v))
        else:
            b[v[0]].append("".join(v))
    else:
        a[v[-1]].append("".join(v))

s = ""
f = True
for v in a["A"]:
    s += v

    if f:
        f = False
        for p in c["B"]:
            s += p

    if len(b["B"]) > 0:
        p = b["B"][0]
        s += p
        b["B"].remove(p)

if f:
    for p in c["B"]:
        s += p

for v in b["B"]:
    s += v

for k in a:
    if k == "A":
        continue
    for v in a[k]:
        s += v

print(s.count("AB"))

Submission status: Accepted

Solution code:
N = int(input())
 
ans = 0
num_A = 0
num_B = 0
num_BA = 0
for _ in range(N):
  s = input()
  ans += s.count('AB')
  num_A += s.endswith('A')
  num_B += s.startswith('B')
  num_BA += s.startswith('B') * s.endswith('A')

con = min(num_A, num_B)
con -= (num_A == num_B == num_BA != 0)
ans += con
print(ans)

Submission status: Accepted

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

A_count=0
B_count=0
BA_count=0
for u in s:
    cnt+=u.count("AB")
    if u[0]=="B":
        B_count+=1
    if u[-1]=="A":
        A_count+=1
    if u[0]=="B" and u[-1]=="A":
        BA_count+=1
if A_count==B_count==BA_count:
    if A_count==0:
        print(cnt)
    else:
        print(cnt+A_count-1)
else:
    print(cnt+min(A_count,B_count))

Submission status: Accepted

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

ans = 0
k = [0] * 3
for i in range(N):
    ans += s[i].count("AB")
    if s[i][0] == "B" and s[i][-1] == "A":
        k[0] += 1
    elif s[i][0] == "B":
        k[1] += 1
    elif s[i][-1] == "A":
        k[2] += 1

if k[0] >= 1:
    k[0] -= 1
    if k[1] >= 1:
        k[1] -= 1
        k[0] += 1
    if k[2] >= 1:
        k[2] -= 1
        k[0] += 1

print(ans + k[0] + min(k[1], k[2]))

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
aend = 0
bstart = 0
aendbstart = 0
for _ in range(n):
   sl = list(input())
   for i in range(len(sl)-1):
      if sl[i] == "A" and sl[i+1] == "B":
         ans += 1
   if sl[0] == "B" and sl[-1] == "A":
      aendbstart += 1
   elif sl[0] == "B":
      bstart += 1
   elif sl[-1] == "A":
      aend += 1

if aendbstart == 0:
   ans += min(aend, bstart)
elif bstart + aend > 0:
   ans += aendbstart + min(aend, bstart)
else:
   ans += aendbstart - 1
print(ans)

Submission status: Accepted

Solution code:
def two_int():
    N, K = map(int, input().split())
    return N,K

def one_int():
    return int(input())

def one_str():
    return input()

def many_int():
    return list(map(int, input().split()))

N=one_int()

strs=[]
for i in range(N):
    strs.append(one_str())

count = 0
head_B=0
tail_A=0
dual_num=0
for s in strs:
    count +=s.count("AB")
    head_B += 0 if s[0]!="B" else 1
    tail_A += 0 if s[-1]!="A" else 1 
    
    if s[0]=="B" and s[-1]=="A":
        dual_num+=1
    

if N==1:
    print(count)
elif dual_num==head_B==tail_A and head_B>=1:
    print(min(head_B, tail_A) -1 +count)
else:
    print( min(head_B, tail_A)+count)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from operator import itemgetter
sys.setrecursionlimit(10000000)
INF = 10**30

def main():
    n = int(input().strip())
    v = []
    ra = 0
    rb = 0
    both = 0
    ans = 0
    for i in range(n):
        s = input().strip()
        for j in range(len(s)-1):
            if s[j] == 'A' and s[j+1] == 'B':
                ans += 1
        if s[0] != 'B' and s[-1] == 'A':
            ra += 1
        elif s[0] == 'B' and s[-1] != 'A':
            rb += 1
        elif s[0] == 'B' and s[-1] == 'A':
            both += 1

    if ra + rb == 0 and both > 0:
        ans += both - 1
    else:
        ans += min(ra+both, rb+both)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

cntA = 0
cntB = 0
cntT = 0
ans = 0
for i in s:
    if i[0] == 'B' and i[-1] == 'A':
        cntT += 1
    else:
        if i[0] == 'B':
            cntB += 1
        if i[-1] == 'A':
            cntA += 1
    ans += i.count('AB')

if cntT > 1:
    ans += cntT - 1
    cntT = 1

if cntA > 0 and cntB > 0 and cntT > 0:
    ans += 2
    cntT -= 1
    cntA -= 1
    cntB -= 1

if cntT > 0:
    if cntA > 0 and cntA >= cntB:
        cntB += 1
    elif cntB > 0:
        cntA += 1

print(ans + min(cntA, cntB))

Submission status: Accepted

Solution code:
N = int(input())

BA = 0
A = 0
B = 0
num = 0

for i in range(N):
	S = input()
	num += 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

ans = num

if A + B > 0:
	ans += min(A, B) + BA
else:
	ans += max(0, BA-1)

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
AB = 0
bx, ba, xa = 0, 0, 0
for i in range(N):
  S = input()
  for j in range(len(S)-1):
    if S[j:j+2] == "AB":
      AB += 1
  if S[0] == 'B' and S[len(S)-1] == 'A':
    ba += 1
  elif S[0] == 'B' and S[len(S)-1] != 'A':
    bx += 1
  elif S[0] != 'B' and S[len(S)-1] == 'A':
    xa += 1
#print(xa, ba, bx)
if ba > 0:
  if xa > 0 and bx > 0:
    xa -= 1
    bx -= 1
    AB += ba + 1
  elif xa > 0 and bx == 0:
    xa -= 0
    AB += ba
  elif bx > 0 and xa == 0:
    bx -= 1
    AB += ba
  elif xa == 0 and bx == 0:
    AB += ba - 1
AB += min(xa, bx)
print(AB)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())
s = []
B_A = []
__A = []
B__ = []
abin = []

for i in range(n):
    si = input()
    s.append(si)
    c = 0
    if si[0] == "B":
        if si[len(si)-1] == "A":
            B_A.append(i)
        else:
            B__.append(i)
    else:
        if si[len(si)-1] == "A":
            __A.append(i)
    for j in range(1,len(si)):
        if si[j]== "B" and si[j-1] == "A":
            c += 1
    abin.append(c)

a = len(__A)
b = len(B__)
ab = len(B_A)
ans = sum(abin)

if ab > 0:
    renketu = ab
    if a > 0:
        renketu += 1
        a -= 1
    if b > 0:
        renketu += 1
        b -= 1
    renketu -= 1
else:
    renketu = 0

renketu += min(a,b)
    

print(ans + renketu)

Submission status: Accepted

Solution code:
n = int(input())

ans = 0
a = b = b_a = 0

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

if b_a > 0:
    if a > 0 and b > 0:
        ans += b_a + 1
        ans += min(a-1, b-1)
    elif a > 0 or b > 0:
        ans += b_a
    else:
        ans += b_a - 1
elif a > 0 and b > 0:
    ans += min(a, b)

print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
res = 0
a = 0
b = 0
ab = 0
for _ in range(N):
  s = input()[: -1]
  res += s.count("AB")
  a += s[-1] == "A"
  b += s[0] == "B"
  ab += (s[-1] == "A" and (s[0] == "B"))
ab = ab > 0 and (a == b == ab)
print(res + min(N - 1, a - ab, b - ab))

Submission status: Accepted

Solution code:

def main():
    N = int(input())
    cnt = 0
    ab,a,b = 0,0,0
    for _ in range(N):
        s = input()
        for i in range(len(s)-1):
            if s[i:i+2]=="AB":
                cnt += 1
        if s[0]=="B" and s[-1]=="A":
            ab += 1
        elif s[0]=="B":
            b +=1
        elif s[-1]=="A":
            a +=1

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

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())
cntAB = 0
A, B = [], []
for i in range(N):
  s = input()
  cntAB += s.count('AB')
  if s[0] == 'B': B.append(i)
  if s[-1] == 'A': A.append(i)

setAB = set(A).intersection(B)
len_setAB = len(setAB)
if len_setAB > 0:
  if len_setAB == len(A) and len_setAB == len(B):
    print(cntAB+len_setAB-1)
  elif len_setAB == len(A) or len_setAB == len(B):
    print(cntAB+len_setAB)
  else:
    print(cntAB+min(len(A),len(B),N-1))
else:
  print(cntAB+min(len(A),len(B),N-1))

Submission status: Accepted

Solution code:
import re

n = int(input())
ss = [input() for _ in range(n)]

count_ab = 0
b_a = 0
__a = 0
b__ = 0

for si in ss:
  count_ab += len(re.findall('AB',si))
  if si[0]=='B' and si[-1]=='A':
    b_a += 1
  elif si[0]=='B':
    b__ += 1
  elif si[-1]=='A':
    __a += 1
  else:
    pass

if b_a == 0:
  print(count_ab + min(__a,b__))
else:
  if __a == 0 and b__ == 0:
    print(count_ab + b_a - 1)
  else:
    print(count_ab + b_a + min(__a,b__))

Submission status: Accepted

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


def main():
    N = int(input())
    ba = []
    ca = []
    bc = []
    cc = []
    for _ in range(N):
        s = input().strip()
        b = (s[0] == "B")
        a = (s[-1] == "A")
        if b and a:
            ba.append(s)
        elif not b and a:
            ca.append(s)
        elif b and not a:
            bc.append(s)
        else:
            cc.append(s)
    S = ""
    if ca:
        S += ca.pop()
    for s in ba:
        S += s
    if bc:
        S += bc.pop()
    while ca or bc:
        if ca:
            S += ca.pop()
        if bc:
            S += bc.pop()
    for s in cc:
        S += s
    print(S.count("AB"))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N=int(input())
ba=bx=xa=0
ans=0
for i in range(N):
    s=input()
    ans+=s.count('AB')
    if s.startswith('B') and s.endswith('A'):
        ba+=1
    elif s.startswith('B'):
        bx+=1
    elif s.endswith('A'):
        xa+=1

if ba==0:
    ans+=min(bx,xa)
elif ba>0:
    if bx+xa>0:
        ans+=ba+min(bx,xa)
    elif bx+xa==0:
        ans+=ba-1

print(ans)

Submission status: Accepted

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

ret = 0
a, b, c = 0, 0, 0
for i in range(N) :
  ret += s[i].count('AB')
  if s[i][-1] == 'A' and s[i][0] == 'B' :
    c += 1
  elif s[i][-1] == 'A' :
    a += 1
  elif s[i][0] == 'B' :
    b += 1

if c >= 2 :
  ret += c - 1
  c = 1
  
if c > 0 and a > 0 :
  a -= 1
  ret += 1
if c > 0 and b > 0 :
  b -= 1
  ret += 1
  
ret += min(a, b)
print(ret)

Submission status: Accepted

Solution code:
import sys
import re
n = int(input())
a = 0
b = 0
a_b = 0
cnt = 0
for i in range(n):
    s = sys.stdin.readline().strip()
    cnt += len(re.findall("AB", s))
    a += s[0] == "B"
    b += s[-1] == "A"
    a_b += (s[0] == "B" and s[-1] == "A")
plus = 0
if a == b == a_b != 0:
    plus -= 1
plus += min(a, b)
print(cnt + plus)

Submission status: Accepted

Solution code:
n = int(input())
word_list = []
count = 0
top_b = 0
bottom_a = 0
ba = 0

for i in range(n):
    s = input()
    word_list.append(s)

for i in word_list:
    if i[0] == 'B' and i[-1] == 'A':
        ba += 1
    elif i[0] == 'B':
        top_b += 1
    elif i[-1] == 'A':
        bottom_a += 1
    for j in range(len(i)-1):
        if i[j] == 'A' and i[j+1] == 'B':
            count += 1

if ba:
    if top_b == 0 and bottom_a == 0:
        count += (ba - 1)
    else:
        count += min(ba + top_b, ba + bottom_a)
else:
    count += min(bottom_a, top_b)

print(count)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.read

N, *s = map(str, read().split())
answer = 0
first = 0
last = 0
BA = 0
for i in s:
    answer += i.count('AB')
    if i[0] == 'B' and i[-1] == 'A':
        BA += 1
        continue

    if i[0] == 'B':
        first += 1
    if i[-1] == 'A':
        last += 1

if BA:
    answer += BA - 1
    if first:
        answer += 1
        first -= 1
    if last:
        answer += 1
        last -= 1

answer += min(first, last)
print(answer)

Submission status: Accepted

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

for _ in range(n):
    S.append(input())
sum_=0
a=0
b=0
c=0
for s in S:
    sum_ += s.count("AB")
    if s[0] =="B" and s[-1] =="A":
        c+=1
    elif s[0] =="B" and s[-1] !="A":
        b+=1
    elif s[-1] =="A" and s[0] !="B":
        a+=1
if c == 0:
    print(sum_+min(a,b))
else:
    if a+b ==0:
        print(sum_+ c-1)
    else:
        print(sum_+ c+min(a,b))

Submission status: Accepted

Solution code:
N = int(input())
AB = 0
B_ = 0
_A = 0
B_A = 0
for i in range(N):
    s = input()
    AB += s.count('AB')
    if s[0]=='B':
        B_ += 1
    if s[-1]=='A':
        _A += 1
    if s[0]=='B' and s[-1]=='A':
        B_A += 1
if B_==_A==B_A:
    if B_A==0:
        print(AB)
    else:
        print(AB+B_A-1)
else:
    print(AB+min(B_,_A))

Submission status: Accepted

Solution code:
n = int(input())

inAB = 0
B_A = 0
x_A = 0
B_x = 0

for _ in range(n):
    s = input()
    if s[0] == "B" and s[-1] == "A":
        B_A += 1
    elif s[0] == "B":
        B_x += 1
    elif s[-1] == "A":
        x_A += 1
    inAB += s.count("AB")

ans = inAB
ans += min(x_A, B_x)
if B_A != 0:
    if x_A == 0 and B_x == 0:
        ans += B_A - 1
    else:
        ans += B_A

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())
A = 0
B = 0
AB = 0
ans = 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" and s[-1] == "A":
        AB += 1
    elif s[0] == "B":
        B += 1
    elif s[-1] == "A":
        A += 1
if AB > 0:
    if A + B > 0:
        ans += AB + min(A,B)
    elif A + B == 0:
        ans += AB - 1
else:
    ans += min(A,B)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
A = 0
B = 0
AB = 0
ans = 0
S = [ input() for i in range(n)]
Bs = []
As = []
ABs = []
#print()
for i in range(n):
    s = S[i]
    for i in range(len(s)-1):
        if s[i] == "A" and s[i+1] == "B":
            ans += 1
            #print(s)
    if s[0] == "B" and s[-1] == "A":
        AB += 1
        ABs.append(s)
    elif s[0] == "B":
        B += 1
        Bs.append(s)
    elif s[-1] == "A":
        A += 1
        As.append(s)
#print(ABs)
#print(As)
#print(Bs)
#print(ans)
#ans += AB
#print(ans)
if AB > 0:
    if A + B > 0:
        ans += AB + min(A,B)
    elif A + B == 0:
        ans += AB - 1
else:
    ans += min(A,B)
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
ans=0
aend=0
bstart=0
aendbstart=0
for i in range(n):
  s=input()
  ans+=s.count("AB")
  if s[0]=="B" and s[-1]=="A":
    aendbstart+=1
  elif s[0]=="B":
    bstart+=1
  elif s[-1]=="A":
    aend+=1
anow=False
if aend>0:
  aend-=1
  anow=True
elif aendbstart>0:
  aendbstart-=1
  anow=True
if anow:
  ans+=aendbstart
if anow and bstart>0:
  bstart-=1
  ans+=1
  anow=False
if aend>0 and bstart>0:
  ans+=min(aend,bstart)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
cnt = 0
BX = 0
BA = 0
XA = 0
for _ in range(N):
    S = input()
    for i in range(1, len(S)):
        if S[i - 1] == 'A' and S[i] == 'B':
            cnt += 1
    if S[0] == 'B' and S[-1] == 'A':
        BA += 1
    elif S[0] == 'B':
        BX += 1
    elif S[-1] == 'A':
        XA += 1

if BA > 0:
    cnt += BA - 1
    if BX > 0:
        cnt += 1
        BX -= 1
    if XA > 0:
        cnt += 1
        XA -= 1
cnt += min(XA, BX)
print(cnt)

Submission status: Accepted

Solution code:
N=int(input())
s=0
BA=0
XA=0
BX=0
for i in range(N):
    st=input()
    s+=st.count("AB")
    f1=0
    f2=0

    
    if(st[0]=="B"):f1=1
    if(st[-1]=="A"):f2=1

    if(f1 and f2):
        BA+=1
    elif(f1):
        BX+=1
    elif(f2):
        XA+=1
if(XA==0 and BX==0 and BA<2):
    print(s)
elif(XA==0 and BX==0):
    print(s+BA-1)
else:
    print(s+min(XA+BA,BX+BA))

Submission status: Accepted

Solution code:
N = int(input())
C = {0:0,1:0,2:0}
cnt = 0
for _ in range(N):
    s = input().strip()
    if s[0]=="B" and s[-1]!="A":
        C[0] += 1
    elif s[0]!="B" and s[-1]=="A":
        C[1] += 1
    elif s[0]=="B" and s[-1]=="A":
        C[2] += 1
    for i in range(len(s)-1):
        if s[i:i+2]=="AB":
            cnt += 1
if C[2]>0:
    cnt += C[2]-1
    if C[0]>0:
        cnt += 1
        C[0] -= 1
    if C[1]>0:
        cnt += 1
        C[1] -= 1
cnt += min(C[0],C[1])
print(cnt)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    ab_cnt = 0
    b_cnt = 0
    a_cnt = 0
    ans = 0
    for _ in range(N):
        S = input()
        ans += S.count("AB")
        if S[0] == "B" and S[-1] == "A":
            ab_cnt += 1
        elif S[0] == "B":
            b_cnt += 1
        elif S[-1] == "A":
            a_cnt += 1
    if ab_cnt > 1:
        ans += max(ab_cnt - 1, 0)
        ab_cnt = 1
    if a_cnt <= b_cnt:
        ans += a_cnt
        a_cnt = 0
        b_cnt -= a_cnt
    elif b_cnt < a_cnt:
        ans += b_cnt
        b_cnt = 0
        a_cnt -= b_cnt
    if ab_cnt > 0 and (a_cnt > 0 or b_cnt > 0):
        ans += 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# 1. 両端にaもbも含まれないもしくは「先頭がaで末尾がb」は分けて考える 最後にテキトーに加えてやる
# 2. 「先頭がb」「末尾がa」「先頭がbで末尾がa」
# cca
# caa
# bac
# bbc
# bccca < -これは連結したほうがよさそう連結したあとに左にooa右にbooを加える
# あまったooaとbooで適当にくっつける
n = int(input())
ans = 0
both = 0
a, b = 0, 0
for _ in range(n):
    s = input()
    if s[0] != "B" and s[-1] != "A":
        ans += s.count("AB")
    else:
        if s[0] == "B" and s[-1] == "A":
            both += 1
            ans += s.count("AB")
        elif s[0] == "B":
            b += 1
            ans += s.count("AB")
        elif s[-1] == "A":
            a += 1
            ans += s.count("AB")
# 両脇にあるやつを連結
if both > 0:
    ans += both - 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())
hb = 0
ta = 0
hbta = 0
ab = 0
for i in range(n):
  s = input()
  ab += s.count('AB')
  f = (s[len(s) -1] == 'A')
  g = (s[0] == 'B')
  if f and g:
    hbta += 1
  elif f:
    ta += 1
  elif g:
    hb += 1
if not hb and not ta and not hbta:
  print(ab)
elif not hb and not ta:
  print(ab + hbta - 1)
elif not hb or not ta:
  print(ab + hbta)
else:
  print(ab + hbta + min(hb, ta))

Submission status: Accepted

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

ans = 0
check = 0
for s in S:
    if s[0] == "B":
        begin_b += 1
    if s[-1] == "A":
        last_a += 1
    if s[0] == "B" and s[-1] == "A":
        check += 1
    for i in range(len(s)-1):
        if s[i] == "A" and s[i+1] == "B":
            ans += 1
ans += min(last_a, begin_b)
if last_a == begin_b and check == begin_b and begin_b != 0:
    ans -= 1
print(ans)

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

while A > 0 or BA > 0:
  if A > 0:
    A -= 1
  elif BA > 0:
    BA -= 1
  else:
    break
  if BA > 0:
    BA -= 1
    A += 1
    ans += 1
  elif B > 0:
    B -= 1
    ans += 1
  else:
    break
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
S=[input() for i in range(N)]
count=0
countA=0
countB=0
countB_A=0
for s in S:
    countA+=s[0]=="B"
    countB+=s[-1]=="A"
    countB_A+=s[0]=="B" and s[-1]=="A"
    for i in range(len(s)-1):
        count+=s[i]+s[i+1]=="AB"
if countA==countB==countB_A and countB_A:
    count-=1
print(count+min(countA,countB))

Submission status: Accepted

Solution code:
import sys

#+++++

def count_ab(a_s):
	ret=0
	is_a=False
	for c in a_s:
		if c == 'A':
			is_a=True
		elif is_a and c == 'B':
			ret+=1
			is_a=False
		else:
			is_a=False
	return ret
		
def main():
	n=int(input())
	sl=[]
	ret=0
	n_top_b=0
	n_buttom_a=0
	n_tb_ab=0
	
	for i in range(n):
		aa = input()
		ret+=count_ab(aa)
		if aa[0]=='B':
			n_top_b+=1
		if aa[-1]=='A':
			n_buttom_a+=1
		if aa[0]=='B' and aa[-1]=='A':
			n_tb_ab+=1
	
	min_n_ab=min(n_buttom_a, n_top_b)
	if min_n_ab == 0:
		return ret
	
	ret += min_n_ab
	if n_buttom_a==n_top_b and n_top_b==n_tb_ab:
		ret -= 1
	
	return ret
	
	
#+++++
isTest=False

def pa(v):
	if isTest:
		print(v)

if __name__ == "__main__":
	if sys.platform =='ios':
		sys.stdin=open('inputFile.txt')
		isTest=True
	else:
		pass
		#input = sys.stdin.readline
			
	ret = main()
	if ret is not None:
		print(ret)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import numpy as np

N = int(input())

cnt_AB = 0
xA = 0
Bx = 0
BA = 0
xx = 0
for i in range(N):
  s = input()
  cnt_AB += s.count('AB')
  if s[0] == 'B':
    if s[-1] == 'A':
      BA += 1
    else:
      Bx += 1
  else:
    if s[-1] == 'A':
      xA += 1
    else:
      xx += 1

A = xA + BA
B = Bx + BA
ans = cnt_AB

if A > B:
  ans += B
elif A < B:
  ans += A
elif A > 0:
  ans += A
  if xA == 0:
    ans -= 1

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = 0
B = 0
AB = 0
BtoA = 0
for i in range(N):
    s = input()
    AB += s.count('AB')
    if s[-1] == 'A':
        A += 1
    if s[0] == 'B':
        B += 1
    if s[0] == 'B' and s[-1] == 'A':
        BtoA += 1
if A == B == BtoA:
    A -= 1
answer = AB + max(0, min(N-1, min(A, B)))
print(answer)

Submission status: Accepted

Solution code:
from collections import Counter

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

cnt=0
cnt_a=0
cnt_b=0
cnt_ab=0
for i in range(n):
    if s[i][0]=='B' and s[i][-1]=='A':
        cnt_ab+=1
    elif s[i][0]=='B':
        cnt_b+=1
    elif s[i][-1]=='A':
        cnt_a+=1
    cnt+=s[i].count('AB')
if cnt_ab==0:
    ans=cnt+min(cnt_a,cnt_b)
else:
    if cnt_a==0 and cnt_b==0:
        ans=cnt+cnt_ab-1
    else:
        ans=cnt+cnt_ab+min(cnt_a,cnt_b)

print(ans)

Submission status: Accepted

Solution code:
import math

def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    # divisors.sort()
    return divisors

#a = list(map(int, input().split()))

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


#1:25
n = int(input())
ss=[]
ans=0
counta=0
countb=0
countab=0

for i in range(n):
    ss.append(input())
    ca = 'A' == ss[-1][-1]
    cb = 'B' == ss[-1][0]
    for i in range(len(ss[-1])-1):
        if(ss[-1][i]=='A' and ss[-1][i+1]=='B'):
            ans+=1
            #print(ss[-1])
    if(ca and cb):
        countab+=1
    elif(ca):
        counta+=1
    elif(cb):
        countb+=1
if(counta+countb==0):
    print(ans+max(countab-1,0))
elif(counta>=1 and countb>=1):
    print(ans+min(counta,countb)+countab)
else:
    print(ans+countab)
#print(ans,counta,countab,countb)

Submission status: Accepted

Solution code:
N = int(input())

A = []
B = []

ans = 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[0] == "B":
        B.append(i)
    if s[-1] == "A":
        A.append(i)

A = set(A)
B = set(B)
#print(A, B)
if len(A) == len(B):
    ans += len(A)
    if len(A&B) == len(A) and len(A)>0:
        ans -= 1
elif len(A)> len(B):
    ans += len(B)
else:
    ans += len(A)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
s = [input() for i in range(N)]
minAB = 0
AB = [0, 0]
count = 0
for i, x in enumerate(s):
    minAB += x.count("AB")
    if x[-1] == "A":
        AB[0] += 1
    if x[0] == "B":
        AB[1] += 1
        if x[-1] == "A":
            count += 1
if count != max(AB) or count == 0:
    print(minAB + min(AB))
else:
    print(minAB + min(AB)-1)

Submission status: Accepted

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

N=int(readline())
s=[readline().rstrip().decode("utf-8") for _ in range(N)]
#print(s)

A,B,AB,BA=0,0,0,0
for ss in s:
  for i in range(len(ss)-1):
    if ss[i]=="A" and ss[i+1]=="B":
      AB+=1
  if ss[-1]=="A": A+=1
  if ss[0]=="B": B+=1
  if ss[-1]=="A" and ss[0]=="B": BA+=1
A-=BA
B-=BA
#print("AB,BA,A,B:",AB,BA,A,B)

if BA>1:
  AB+=BA-1
  BA=1
#print("AB,BA,A,B:",AB,BA,A,B)

if BA==1:
  if A>0 or B>0:
    if A>0:
      AB+=1
      A-=1
    if B>0:
      AB+=1
      B-=1
    BA-=1
#print("AB,BA,A,B:",AB,BA,A,B)

AB+=min(A,B)
print(AB)