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 fractions import gcd
from datetime import date, timedelta
from heapq import*
import math
from collections import defaultdict, Counter, deque
import sys
from bisect import *
import itertools
import copy
sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7


def main():
    n = int(input())
    d = defaultdict(int)
    ans = 0
    for i in range(n):
        s = input()
        ans+=s.count("AB")
        if s[0] == "B" and s[-1] == "A":
            d[0] += 1
        elif s[0] == "B":
            d[1]+=1
        elif s[-1] == "A":
            d[2] += 1

    if d[0] > 0:
        ans += d[0] - 1
        if d[1] > 0 and d[2] > 0:
            ans += 2
            ans += min(d[1] - 1 , d[2] - 1)
        elif d[1] > 0 and d[2] == 0:
            ans += 1
        elif d[1] == 0 and d[2] > 0:
            ans += 1
    else:
        ans+=min(d[1] , d[2])

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n=int(input())
countab=0
counta=0
countb=0
count=0
for i in range(n):
  w=input()
  num=len(w)
  for j in range(num-1):
    if w[j]=="A" and w[j+1]=="B":
      count+=1
  if w[0]=="B" and w[-1]=="A":
    countab+=1
  elif w[0]=="B":
    countb+=1
  elif w[-1]=="A":
    counta+=1
ans=count
if countab==0:
  pass
else:
  ans+=countab-1
if counta==0 and countb==0:
  print(ans)
else:
  if countab==0:
    pass
  else:
    ans+=1
  ans+=min(counta,countb)
  print(ans)

Submission status: Accepted

Solution code:
from sys import stdin
N = int(stdin.readline().rstrip())
ans = 0
c1 = 0
c2 = 0
c3 = 0
for _ in range(N):
    s = (stdin.readline().rstrip())
    ans += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        c1 += 1
    elif s[0] == "B":
        c2 += 1
    elif s[-1] == "A":
        c3 += 1
if c1 == 0:
    ans += min(c2,c3)
else:
    if c2 + c3 == 0:
        ans += (c1-1)
    else:
        ans += (c1 + min(c2,c3))
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
word = []
ab = 0
a = 0
b = 0
mid = 0

for i in range(n):
    s = str(input())
    if s[0] == "B" and s[-1] == "A":
        ab += 1
    elif s[0] == "B":
        a += 1
    elif s[-1] == "A":
        b += 1
    for k in range(len(s) - 1):
        if s[k] == "A" and s[k + 1] == "B":
            mid += 1

# print(a, b, ab, mid)
if ab > 0:
    mid += ab - 1
    if a == 0 and b == 0:
        mid += 0
    elif a == 0 or b == 0:
        mid += 1
    else:
        mid += 2 + min(a - 1, b - 1)

else:
    mid += min(a, b)
print(mid)

Submission status: Accepted

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


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

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N=int(input())
s=''
point=0
q1,q2,q3=0,0,0 #q1はBA q2はBの最初のみ q3はAの末尾のみ
for j in range(N):
    n=str(input())
    point+=n.count("AB")
    if n[0]=="B" and n[len(n)-1]=="A":
      q1+=1  
    elif n[0]=="B":
      q2+=1
    elif n[len(n)-1]=="A":
      q3+=1
    else:
      pass
if q1>=1:
  if q2==0 and q3==0:
    print(q1-1+point)
  elif q2==0 or q3==0:
    print(q1-1+1+point)
  else:
    print(q1-1+point+2+min(q2-1,q3-1))
else:
  print(min(q2,q3)+point)

Submission status: Accepted

Solution code:
N = int(input())
cnt = 0
A = 0
B = 0
BA = 0
for _ 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:
    ans = cnt + min(A, B)
else:
    ans = cnt + 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:
n = int(input())
c, fb, la, both = 0, 0, 0, 0
for _ in range(n):
  s = input()
  c += s.count("AB")
  if s[0] == "B" and s[-1] == "A":
    both += 1
  else:
    if s[0] == "B":
      fb += 1
    if s[-1] == "A":
      la += 1
if both == 0:
  c += min(fb, la)
else:
  if fb+la > 0:
    c += both + min(fb, la)
  else:
    c += both-1
print(c)

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heapify,heappop,heappush
import sys,bisect,math,itertools,string,queue
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())
def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

n = inp()
s = [input() for i in range(n)]
cnt = 0
a = 0
b = 0
ba = 0
for i in s:
    if i[0] == 'B' and i[-1] == 'A':
        ba += 1
    elif i[0] == 'B':
        b += 1
    elif i[-1] == 'A':
        a += 1
    for j in range(len(i)-1):
        if i[j] == 'A' and i[j+1] == 'B':
            cnt += 1
if a == b == ba == 0:
    print(cnt)
elif a == b == 0:
    print(cnt + ba-1)
else:
    print(cnt + min(a,b) + ba)

Submission status: Accepted

Solution code:
n=int(input())
s=[list(input()) for i in range(n)]
count=0
countA=0
countB=0
countBA=0
for i in range(n):
    for j in range(len(s[i])-1):
        if s[i][j]=='A' and s[i][j+1]=='B':
            count+=1

for i in range(n):
    if s[i][0]=='B' and s[i][-1]=='A':
        countBA+=1
        
    elif s[i][0]=='B':
        countB+=1
    
    elif s[i][-1]=='A':
        countA+=1

if  (countA>0 or countB>0) and countBA>0:
    count+=countBA-1+min(countB+1,countA+1)

else:
    count+=min(countB,countA)+max(countBA-1,0)
    
print(count)

Submission status: Accepted

Solution code:

N = int(input())
AB = 0
LA = 0
FB = 0
LAFB = 0

for i in range(N):

    s = input()
    fbf = False
    laf = False

    for j in range(len(s)):

        

        if j == 0 and s[j] == "B":
            fbf = True

        if j == len(s) - 1:
            if s[j] == "A":
                laf = True

        elif s[j] == "A" and s[j+1] == "B":
            AB += 1


    if fbf and laf:
        LAFB += 1
    elif laf:
        LA += 1
    elif fbf:
        FB += 1

if LAFB > 0:
    AB += LAFB - 1

    if LA > 0:
        LA -= 1
        AB += 1

    if FB > 0:
        FB -= 1
        AB += 1

print (AB + min(FB,LA))

Submission status: Accepted

Solution code:
#import math
#import copy
#import sys
#import bisect
#input = sys.stdin.readline
mod=10**9+7
def swap(a,b):
    c=a
    a=b
    b=c
    return a,b
def factorial(x): #階乗計算
    n=1
    for i in range(x):
        n=(n*(i+1))%mod
    return n

def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a%b)
def lcm(a, b):
    return((a*b)//gcd(a,b))
def div(x): #約数配列
    div=[1]
    check=2
    while(x!=1 and check <= int(x**0.5)+2):
        if(x%check==0):
            div.append(check)
            while(x%check==0):
                x=x//check
        check+=1
    if x != 1:
      div.append(x)
    return div
def div2(x): #素因数分解配列
    div2=[]
    check=2
    while(x!=1 and check <= int(x**0.5)+2):
        while x%check==0:
            div2.append(check)
            x/=check
        check+=1
    if x != 1:
      div2.append(x)
    return div2

def main():
    # x,y = map(int,input().split())           x=1,y=2
    # a = input().split()                      a=['1','2','3',...,'n']
    # a = list(map(int,input().split()))       a=[1,2,3,4,5,...,n]
    # li = input().split('T')	              FFFTFTTFF => li=['FFF', 'F', '', 'FF']
    # 複数行の「1 2 3 4」型の入力を一配列に
    # x = sorted([list(map(int, input().split())) for _ in range(n)])
    # ソート x.sort(key=lambda y:y[1])
    # [chr(i) for i in range(97, 97+26)] 英語小文字リスト
    # [chr(i) for i in range(65, 65+26)] 英語大文字リスト atcoder
    # ord(c) chr(2) alphabet <=> number
    n=int(input())
    cnt=a=b=ba=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[len(s)-1]=="A":
            ba+=1
        elif s[0]=="B":
            b+=1
        elif s[len(s)-1]=="A":
            a+=1
    if ba==0:print(cnt+min(a,b))
    else:
        print(cnt+ (ba-1 if a+b==0 else ba+min(a,b)) )
main()

Submission status: Accepted

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

Submission status: Accepted

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

def main():
    N = int(input())
    s = [input().strip() for i in range(N)]
    
    ans = 0
    ba = 0
    b_ = 0
    _a = 0
    for c in s:
        ans += c.count("AB")
        if c[0] == "B":
            if c[-1] == "A":
                ba += 1
            else:
                b_ += 1
        elif c[-1] == "A":
            _a += 1
    if ba == 0:
        ans += min(b_, _a)
    elif b_ + _a > 0:
        ans += ba + min(b_, _a)
    elif b_ + _a == 0:
        ans += ba - 1
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n=int(input())
s=[str(input()) for i in range(n)]
#print(s)
ans=0
x=0
y=0
z=0
for i in range(n):
    ans+=s[i].count('AB')
    if s[i][0]=='B' and s[i][-1]=='A':
        x+=1
        y+=1
        z+=1
    elif s[i][-1]=='A':
        x+=1
        z+=1
    elif s[i][0]=='B':
        y+=1
        z+=1
p=(x-1 if x==y==z>0 else min(x,y))
print(ans+p)

Submission status: Accepted

Solution code:
n = int(input())

b = 0
a = 0
ab = 0
ex = 0

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

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())

B_ = 0
_A = 0
BA = 0
inner = 0

for i in range(N):
    s = list(input())
    for j in range(1,len(s)):
        if s[j-1] == "A" and s[j] == "B":
            inner += 1
    if s[0] == "B" and s[-1] == "A":
        BA += 1
    elif s[0] == "B":
        B_ += 1
    elif s[-1] == "A":
        _A += 1

#print(BA,B_,_A)

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

Submission status: Accepted

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

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

if a==0 and b==0 and ry!=0:
  print(na+ry-1)
else:
  print(na+ry+1+min(a-1,b-1))

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
bn, an, ban = 0, 0, 0
for _ in range(n):
    s = input()
    if s[0] == "B" and s[-1] == "A": ban += 1
    elif s[0] == "B": bn += 1
    elif s[-1] == "A": an += 1
    for i in range(1, len(s)):
        if s[i] == "B" and s[i-1] == "A": ans += 1
if ban:
    ans += ban - 1
    if bn:
        ans += 1
        bn -= 1
    if an:
        ans += 1
        an -= 1
ans += min(bn, an)
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

N = int(input())
S = [input()[:-1] for _ in range(N)]
ans = 0

end_A = 0
start_B = 0
A_B = 0
for s in S:
    if s[0] == "B"and s[-1] == "A":
        A_B += 1
    elif s[0] == "B":
        start_B += 1
    elif s[-1] == "A":
        end_A += 1
    for a, b in zip(s, s[1:]):
        if a == "A" and b == "B":
            ans += 1

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

print(ans+add)

Submission status: Accepted

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]
N=int(input())
a,A,B,C=0,0,0,0
for i in range(N):
    s=input()
    for j in range(len(s)-1):
        if s[j]=="A" and s[j+1]=="B":
            a+=1
    if s[0]=="B":
        A+=1
    if s[-1]=="A":
        B+=1
        if s[0]=="B":
            C+=1
if A==B==C:
    a+=max(0,C-1)
else:
    a+=min(A,B)
print(a)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
N=int(input())

l=[0]*3
ans=0
for i in range(N):
    S=(input())
    ans+=S.count("AB")
    if S[0]=="B" and S[-1]=="A":
        l[0]+=1
    elif S[0]=="B":
        l[1]+=1
    elif S[-1]=="A":
        l[2]+=1
if l[0]>0:
    ans+=(l[0]-1)
    if l[1]>0:
        l[1]-=1
        ans+=1
    if l[2]>0:
        l[2]-=1
        ans+=1
ans+=min(l[1],l[2])
    
#print(l)
print(ans)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    ls = [input() for _ in range(n)]
    acount = 0
    bcount = 0
    abcount = 0
    bacount = 0
    for s in ls:
        abcount += s.count("AB")
        if s[0] =="B" and s[-1] =="A":bacount += 1
        elif s[0] =="B":bcount += 1
        elif s[-1] =="A":acount += 1

    if acount == 0 and bcount == 0:
        if bacount > 0:
            bacount -= 1
        print(abcount+bacount)
    elif acount == 0 or bcount == 0:
        print(abcount+bacount)
    else:
        print(abcount+bacount+min(acount,bcount))

main()

Submission status: Accepted

Solution code:
# 2019/10/14
import sys
input=sys.stdin.readline

n=int(input())
cnt=0
b_a=0
a=0
b=0
for i in range(n):
    s=input().rstrip('\n')
    cnt+=s.count('AB')
    is_b=s[0]=='B'
    is_a=s[-1]=='A'
    if is_b or is_a:
        if is_b and is_a:b_a+=1
        elif is_b:b+=1
        else:a+=1
    


if b_a:
    cnt+=b_a-1
    if a==b and a>0:
        a-=1;b-=1
        cnt+=2
    else:
        if abs(a-b)>0:
            cnt+=1
cnt+=min(a,b)

print(cnt)

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  n=I()
  ans=0

  _ba=0
  _b=0
  _a=0
  for _ in range(n):
    s=S()
    ans+=s.count('AB')

    if s[0]=='B':
      if s[-1]=='A':
        _ba+=1
      else:
        _b+=1
    else:
      if s[-1]=='A':
        _a+=1

  ans+=max(0,_ba-1)

  if _ba>0:
    if _b>0:
      ans+=1
      _b-=1
    if _a>0:
      ans+=1
      _a-=1

  # if _ba>0:
  #   _b+=1
  #   _a+=1

  ans+=min(_b,_a)

  return ans

# main()
print(main())

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  n=I()
  ans=0

  _ba=0
  _b=0
  _a=0
  for _ in range(n):
    s=S()
    ans+=s.count('AB')

    if s[0]=='B':
      if s[-1]=='A':
        _ba+=1
      else:
        _b+=1
    else:
      if s[-1]=='A':
        _a+=1

  ans+=max(0,_ba-1)

  if _ba>0:
    if _b>0:
      ans+=1
      _b-=1
    if _a>0:
      ans+=1
      _a-=1

  if _b>0 and _a>0:
    ans+=min(_b,_a)

  return ans

# main()
print(main())

Submission status: Accepted

Solution code:
N=int(input())

if N==1:
    print(input().count("AB"))
    exit()

BA=0
B_=0
_A=0
cnt=0

for i in range(N):
    s=input()

    if s[0] == "B" and s[-1] == "A":
        BA += 1
    elif s[0] == "B" and s[-1] != "A":
        B_ += 1
    elif s[-1] != "B" and s[-1] == "A":
        _A += 1

    cnt += s.count("AB")


if _A==0 and B_==0:
    ans=max(0,BA-1)+cnt
elif (_A!=0 and B_==0) or (_A==0 and B_!=0):
    ans=BA+cnt

else:
    ans=BA+1+min(_A-1,B_-1)+cnt

print(ans)

Submission status: Accepted

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

tailA = 0
headB = 0
same = 0
inside = 0
for s in S:
    inside += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        same += 1
    else:
        if s[0] == 'B':
            headB += 1
        if s[-1] == 'A':
            tailA += 1

ans = 0

if same >= 1:
    if tailA >= 1:
        ans += same
        tailA -= 1
    else:
        ans += same - 1

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

ans += max(min(tailA, headB), 0)
print(ans + inside)

Submission status: Accepted

Solution code:
n=int(input())
a=0
b=0
malti=0
origin=0
for i in range(n):
    s=input()
    if s[0]=="B" and s[-1]=="A":
        malti+=1
    elif s[0]=="B" and s[-1]!="A":
        b+=1
    elif s[0]!="B" and s[-1]=="A":
        a+=1
    for i in range(len(s)-1):
        if s[i]=="A" and s[i+1]=="B":
            origin+=1

if a>=1 and b>=1:
    print(origin+malti+1 +min(a-1,b-1))
elif a==0 and b>=1:
    print(origin+malti)
elif a>=1 and b==0:
    print(origin+malti)
elif a==0 and b==0:
    print(origin+max(malti-1,0))

Submission status: Accepted

Solution code:
N = int(input())
listS = ["" for _ in range(N)]
cntAB = 0
for i in range(N):
    listS[i] = input()
    for j in range(len(listS[i])-1):
        if listS[i][j] == "A" and listS[i][j+1] == "B":
            cntAB += 1
cntA = 0
cntB = 0
BcntA = 0
for s in listS:
    if s[0] == "B" and s[-1] != "A":
        cntB += 1
    if s[0] != "B" and s[-1] == "A":
        cntA += 1
    if s[0] == "B" and s[-1] == "A":
        BcntA += 1
connect = 0
if cntA + cntB == 0 and BcntA > 0:
    connect = BcntA - 1
else:
    connect = min(cntA,cntB) + BcntA
print(connect+cntAB)

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for _ in range(N)]
ans = 0
BA, BX, XA = 0, 0, 0
for s in S:
  ans += s.count('AB')
  if s[0] == 'B' and s[-1] == 'A':
    BA += 1
  elif s[0] == 'B':
    BX += 1
  elif s[-1] == 'A':
    XA += 1

x = max(0, BA - 1)
ans += x
BA -= x
x = min(BA, BX)
ans += x
BA -= x
x = min(BA, XA)
ans += x
BA -= x
ans += min(XA, BX)
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
S=[input() for i in range(n)]
a,b,c=0,0,0
cnt=0
for i in S:
    if i[0]=="B" and i[-1]=="A":c +=1
    elif i[0]=="B":a +=1
    elif i[-1]=="A":b +=1
    for j in range(len(i)-1):
        if i[j]+i[j+1]=="AB":cnt +=1

if c==0:cnt +=min(a,b)
elif a+b==0:cnt +=c-1
elif c!=0 and a+b>0:cnt +=min(a,b)+c
print(cnt)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#%%
n = int(input())
s = []
a = 0
b = 0
c = 0
for i in range(n):
    s.append(input())
    if s[i][0] == 'B' and s[i][-1] != 'A':
        b += 1
    if s[i][-1] == 'A' and s[i][0] != 'B':
        a += 1
    if s[i][0] == 'B' and s[i][-1] =='A':
        c += 1

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

if c == 0:
    ans += min(a, b)
elif c != 0 and a+b != 0:
    ans += c + min(a, b)
else:
    ans += c - 1 
print(ans)

Submission status: Accepted

Solution code:
# div2019C - AB Substrings
def main():
    N, *S = open(0).read().split()
    ans, ab, start_b, end_a = 0, 0, 0, 0
    for s in S:
        if s[0] == "B" and s[-1] == "A":
            ab += 1
        elif s[0] == "B":
            start_b += 1
        elif s[-1] == "A":
            end_a += 1
        ans += s.count("AB")
    if start_b + end_a == 0:
        ans += max(0, ab - 1)
    else:
        ans += ab + min(start_b, end_a)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

ans = 0
ba = 0
xa = 0
bx = 0
for s in S:
  ans += s.count('AB')
  if s[0] == 'B' and s[-1] == 'A':
    ba += 1
  elif s[0] == 'B' and s[-1] != 'A':
    bx += 1
  elif s[0] != 'B' and s[-1] == 'A':
    xa += 1
if xa == 0 and bx == 0:
  ans += max(ba-1,0)
elif (xa == 0 and bx != 0) or (xa != 0 and bx == 0):
  ans += ba
else:
  ans += ba+1 + min(xa-1,bx-1)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
ans = 0
_A = 0
B_ = 0
B_A = 0

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

    if s[-1] == 'A':
        _A += 1

    if s[0] == 'B':
        B_ += 1

    if s[0] == 'B' and s[-1] == 'A':
        B_A += 1

ans += min(_A, B_)
if _A == B_ == B_A != 0:
    ans -= 1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
r = 0
nBA = 0
nA = 0
nB = 0
for i in range(N):
  s = input()
  r += s.count("AB")
  if s[0] == "B" and s[-1] == "A":
    nBA += 1
  elif s[0] == "B":
    nB += 1
  elif s[-1] == "A":
    nA += 1
r += min(nA, nB)
if nA > 0 or nB > 0:
  r += nBA
else:
  r += max(0, nBA-1)
print(r)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
n = int(input())
s = [input() for _ in range(n)]
ans = 0
xa = 0
bx = 0
bxa = 0
for c in s:
    ans += sum(c[i:i + 2] == 'AB' for i in range(len(c) - 1))
    if c[0] == 'B':
        bx += 1
    if c[-1] == 'A':
        xa += 1
    if c[0] == 'B' and c[-1] == 'A':
        bx -= 1
        xa -= 1
        bxa += 1
ans += max(0, bxa - 1)
bxa = 0 + (bxa > 0)
ans += min(xa, bxa)
ans += min(bxa, bx)
rxa = max(0, xa - bxa)
rbx = max(0, bx - bxa)
ans += min(rxa, rbx)
print(ans)

Submission status: Accepted

Solution code:
import sys
def main():
    def input():
        return sys.stdin.readline()[:-1]
    N = int(input())
    ans = 0
    a, b, c = 0, 0, 0
    for k in range(N):
        s = input()
        if s[0] == "B" and s[-1] == "A":
            c += 1
        if s[0] == "B":
            b += 1
        if s[-1] == "A":
            a += 1
        for k in range(len(s)-1):
            if s[k:k+2] == "AB":
                ans += 1
    if c > 0 and a == b == c:
        print(ans + c-1)
    else:
        print(ans + min(a,b))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

n = ni()
s = [lc() for _ in range(n)]

ans = 0

stb_eda = 0
stb = 0
eda = 0

for si in s:
    stmp = "".join(si)
    ans += stmp.count("AB")
    if si[0] == "B" and si[-1] == "A":
        stb_eda += 1
    elif si[0] == "B":
        stb += 1
    elif si[-1] == "A":
        eda += 1

if stb >= eda:
    diff = min(stb - eda, stb_eda)
    eda += diff
    stb_eda -= diff

else:
    diff = min(eda - stb, stb_eda)
    stb += diff
    stb_eda -= diff


if eda > 0 or stb > 0:
    ans += min(eda, stb) + stb_eda
else:
    ans += min(eda, stb) + max(0, stb_eda-1)

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
string_list = [ input() for i in range(n) ]
ans = 0
ab_list = [0, 0, 0]

for i in string_list:
    for j in range(len(i)-1):
        if i[j] == "A" and i[j+1] == "B":
            ans += 1
    if i[0] == "B" and i[-1] == "A":
        ab_list[0] += 1
    elif i[0] == "B":
        ab_list[1] += 1
    elif i[-1] == "A":
        ab_list[2] += 1

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

Submission status: Accepted

Solution code:
N = int(input())

count = 0
both = 0
forward = 0
backward = 0
for i in range(N):
    tmp = list(input())
    if tmp[0] == 'B' and tmp[-1] == 'A':
        both += 1
    elif tmp[0] == 'B' and tmp[-1] != 'A':
        forward += 1
    elif tmp[0] != 'B' and tmp[-1] == 'A':
        backward += 1
    for i in range(len(tmp) - 1):
        if tmp[i] == 'A' and tmp[i + 1] == 'B':
            count += 1

# print ('both', both)
# print ('forward', forward)
# print ('backward', backward)
# print ('count', count)

count += max(0, both - 1)
if both > 0:
    if forward > 0 and backward > 0: #前後どちらも埋めることができる
        forward -= 1
        backward -= 1
        count += 2
    elif forward > 0 and backward == 0: #前しか埋めることができない
        count += 1
        forward -= 1
    elif forward == 0 and backward > 0: #後ろしか埋めることができない
        count += 1
        backward -= 1
count += min(forward, backward)
print (count)

Submission status: Accepted

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

ans = 0
for ss in sss:
    ans += ss.count('AB')

num_A = numB_ = numBA = 0
for ss in sss:
    is_A = ss.endswith('A')
    isB_ = ss.startswith('B')
    if is_A:
        num_A += 1
    if isB_:
        numB_ += 1
    if is_A and isB_:
        numBA += 1

ans += min(num_A, numB_)
if num_A == numB_ == numBA and num_A > 0:
    ans -= 1

print(ans)

Submission status: Accepted

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

import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7

n = int(input())
_A = []
B_ = []
BA = []
cnt = 0
for _ in range(n):
    s = input()
    for i in range(len(s)-1):
        if s[i] == 'A' and s[i+1] == 'B':
            cnt += 1
    if s[0] != 'B' and s[-1] == 'A':
        _A.append(s)
    elif s[0] == 'B' and s[-1] != 'A':
        B_.append(s)
    elif s[0] == 'B' and s[-1] == 'A':
        BA.append(s)
a = len(_A)
b = len(B_)
ba = len(BA)
ans = cnt
if ba >= 1:
    if a + b > 0:
        ans += (ba-1) + min(a,b) + 1
    else:
        ans += ba - 1
else:
    ans += min(a,b)
print(ans)

Submission status: Accepted

Solution code:
class diverta2019C:
    def __init__(self):
        self.N = int(input())
        self.s = [input() for i in range(self.N)]
        self.ans = 0
    
    def solve(self):
        a, b, c = 0, 0, 0
        for i in range(self.N):
            if(self.s[i].count('AB')):
                self.ans += self.s[i].count('AB')
            if(self.s[i][-1] == 'A' and self.s[i][0] == 'B'):
                a += 1
            elif(self.s[i][0] == 'B'):
                b += 1
            elif(self.s[i][-1] == 'A'):
                c += 1
        if(a == 0):
            self.ans += min(b, c)
        elif(b + c > 0):
            self.ans += a + min(b, c)
        else:
            self.ans += a-1
        print(self.ans)

if __name__ == '__main__':
    problem = diverta2019C()
    problem.solve()

Submission status: Accepted

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

ans = 0
BA = 0
BX = 0
XA = 0
for s in S:
    ans += s.count("AB")
    if s[0]=="B" and s[-1]=="A":BA+=1
    elif s[0]=="B":BX+=1
    elif s[-1]=="A":XA+=1
ans += min(BX,XA) + max(0,BA - (BX==XA==0))
print(ans)

Submission status: Accepted

Solution code:
a = int(input())
ba = 0
count = 0
A = 0
B = 0
for i in range(a):
    l = input()
    count += l.count("AB")
    if l[0] == "B" and l[-1] == "A":
        ba += 1
    elif l[0] == "B":
        B += 1
    elif l[-1] == "A":
        A += 1
if ba == 0:
    count += min(A,B)
else:
    if A + B == 0:
        count += ba - 1
    else:
        count += ba + min(A,B)
print(count)

Submission status: Accepted

Solution code:
def solve(n, s):
    num = 0
    a, b, ab = 0, 0, 0
    for i in range(n):
        num += s[i].count("AB")
        if s[i].endswith("A"):
            a += 1
        if s[i].startswith("B"):
            b += 1
        if s[i].endswith("A") and s[i].startswith("B"):
            ab += 1
    a -= ab
    b -= ab
    cnt = 0
    if ab > 0:
        cnt += ab - 1
        if a > 0:
            cnt += 1
            a -= 1
        if b > 0:
            cnt += 1
            b -= 1
    cnt += min(a, b)
    return num + cnt

n = int(input())
s = [input() for i in range(n)]
print(solve(n, s))

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for _ in range(N)]
first_B, last_A, both = 0, 0, 0
ans = 0
for s in S:
    ans += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A': both += 1
    elif s[0] == 'B': first_B += 1
    elif s[-1] == 'A': last_A += 1
if both <= 1:
    if last_A <= first_B: last_A += both
    else: first_B += both
    ans += max(min(first_B, last_A), 0)
else:
    ans += max(both-1, 0) + (1 if first_B else 0) + (1 if last_A else 0) + max(min(first_B-1, last_A-1), 0)
print(ans)