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 collections import deque
from heapq import heappush,heappop
import re
def int_raw():
    return int(input())

def ss_raw():
    return input().split()

def ints_raw():
    return list(map(int, ss_raw()))

INF = 1<<29

N = int_raw()
ss = []
cs = []
end_A = []
start_B = []
both_AB = []
for _ in range(N):
    s = input()
    end_A.append(s[-1]=="A")
    start_B.append(s[0]=="B")
    both_AB.append(end_A[-1] and start_B[-1])
    cs.append(s.count("AB"))
    ss.append(s)


def main():
    n_both_AB = sum(both_AB)
    n_endA = sum(end_A)-n_both_AB
    n_startB = sum(start_B)-n_both_AB
    #n_minAB = min(n_startB,n_endA)
    #n_maxAB = max(n_startB,n_endA)
    ans =0
    is_last_A = False
    while (n_both_AB+n_endA+n_startB)>0:
        if is_last_A:
            if n_both_AB>0:
                n_both_AB-=1
                ans+=1
                is_last_A=True
            elif n_startB>0:
                n_startB-=1
                ans+=1
                is_last_A=False
            else:
                 break
        else:
            if n_endA >0:
                n_endA-=1
                is_last_A=True
            elif n_both_AB>0:
                n_both_AB-=1
                is_last_A=True
            else:
                break
        
        
    return sum(cs)+ans
    """if n_minAB+n_both_AB <n_maxAB:
        return sum(cs)+n_minAB+n_both_AB
    else:
        return sum(cs)+(n_minAB+n_maxAB+n_both_AB)//2"""

print(main())

Submission status: Accepted

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

a = 0
b = 0
ab = 0
c = 0

for i in range(n):
  if s[i][0:1] == 'B':
    b += 1
  if s[i][-1:] == 'A':
    a += 1
  if s[i][0:1] == 'B' and s[i][-1:] == 'A':
    ab += 1

  c += s[i].count('AB')

c2 = min(min(a, b), n-1)

if ab == a and ab == b and ab < n and c2 > 0:
  c2 -= 1

print(c+c2)

Submission status: Accepted

Solution code:
N = int(input())
Sa = 0
Sb = 0
Sab = 0
ans = 0
for i in range(N):
    t = input()
    if t[-1] == 'A' and t[0] == 'B': Sab += 1
    elif t[-1] == 'A': Sa += 1
    elif t[0] == 'B': Sb += 1
    ans += t.count('AB')
if Sab > 0:
    ans += Sab-1
    if Sa > 0 and Sb > 0:
        ans += 2
        Sa -= 1
        Sb -= 1
    elif Sa < Sb: Sa += 1
    else: Sb += 1
ans += min(Sa,Sb)
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
# input
a = int(input())
s = 0
bc = 0
ac = 0
tc = 0
for i in range(a):
    t = input()
    s += t.count('AB')
    if t[:1] == 'B':
        bc += 1
    if t[-1:] == 'A':
        ac += 1
    if t[:1] == 'B' or t[-1:] == 'A':
        tc += 1
if min(bc, ac) == tc and tc > 0:
    o = s + min(bc, ac)-1
else:
    o = s + min(bc, ac)
print(o)

Submission status: Accepted

Solution code:
N = int(input())
L = [input() for _ in range(N)]
ctrAB = 0
lastA = 0
firstB = 0
lAfB = 0
for s in L:
    if s[0] == 'B' and s[-1] == 'A':
        lAfB += 1
    if s[0] == 'B':
        firstB += 1
    if s[-1] == 'A':
        lastA += 1
    ctrAB += s.count('AB')
if lAfB != 0 and lAfB == lastA and lAfB == firstB:
    print(ctrAB + lAfB - 1)
else:
    print(ctrAB + min(lastA,firstB))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# coding: utf-8
def main():
    N = int(input())
    s_i = []
    for _ in range(N):
        s_i.append(input())

    count = 0
    tail_a = 0
    top_b = 0
    both_a_b = 0
    for s in s_i:
        count += s.count("AB")

        if s[-1] == "A":
            if s[0] == "B":
                both_a_b += 1
            else:
                tail_a += 1
        elif s[0] == "B":
            top_b += 1

    #print(count)
    #print(tail_a, top_b, both_a_b)

    if both_a_b > 0:
        count += (both_a_b - 1)
        if tail_a > 0:
            count += 1
            tail_a -= 1
        if top_b > 0:
            count += 1
            top_b -= 1

    if min(tail_a, top_b) > 0:
        count += min(tail_a, top_b)

    print(count)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())
s = [input() for i in range(N)]
l1 = [s[i].count('AB') for i in range(N)]
l2 = [1 if s[i][0] == 'B' else 0 for i in range(N)]
l3 = [1 if s[i][-1] == 'A' else 0 for i in range(N)]
l4 = [l2[i]*l3[i] for i in range(N)]
if max(sum(l2),sum(l3)) == sum(l4):
    a = max(min(sum(l2),sum(l3))-1,0)
else:
    a = min(sum(l2),sum(l3))
print(sum(l1) + a)

Submission status: Accepted

Solution code:
import sys
import collections
ns = lambda: sys.stdin.readline().rstrip()
ni = lambda: int(ns())
nm = lambda: map(int, sys.stdin.readline().split())
nl = lambda: list(nm())
nsm = lambda: map(str, sys.stdin.readline().split())

n = ni()
s = []
ca = 0
cb = 0
ans = 0
both = 0
for i in range(n):
    t = ns()
    if t[0] == 'B' and t[-1] != 'A':
        cb += 1
    elif t[-1] == 'A' and t[0] != 'B':
        ca += 1
    elif t[0] == 'B' and t[-1] == 'A':
        both += 1
    for j in range(1, len(t)):
        if t[j - 1] == 'A' and t[j] == 'B':
            ans += 1
if both > 0:
    ans += both - 1
    if ca > 0 and cb > 0:
        ans += 2
        ans += min(ca - 1, cb - 1)
    elif abs(ca - cb) > 0:
        ans += 1
        ans += min(ca, cb)
    print(ans)
else:
    ans += min(ca, cb)
    print(ans)

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
a =[0 for i in range(n)]
b = [0 for i in range(n)]
c = [0 for i in range(n)]
for i in range(n):
    s = input()
    q = len(s)
    for j in range(q):
        if j == 0 and s[j] == 'B':
            b[i] = 1
        elif j == q-1 and s[j] == 'A':
            a[i] = 1
        if j > 0:
            if s[j] == 'B' and s[j-1] == 'A':
                ans += 1
    if b[i] == 1 and a[i] == 1:
        c[i] = 1
        a[i] = 0
        b[i] = 0



A = sum(a)
B = sum(b)
C = sum(c)
if C >= 1:
    ans += C-1
    if A >= 1 and B >= 1:
        ans += 2 + min(A-1,B-1)
    elif A == 0 and B == 0:
        pass
    else:
        ans += 1
else:
    ans += min(A,B)

print(ans)

Submission status: Accepted

Solution code:
N=int(input())
s=[]
total=0
A=0
B=0
BA=0
for i in range(N):
    tmp=input()
    while True:
        if len(tmp)>=2:
            if "AB" in tmp[:2]:
                total+=1
                tmp=tmp[2:]
            else:
                break
        else:
            break
    while True:
        
        if len(tmp)>=2:
            if "AB" in tmp[-2:]:
                total+=1
                tmp=tmp[-2:]
            else:
                break
        else:
            break
    total+=tmp.count("AB")
    if len(tmp)>0:
        if tmp[0]=="B" and tmp[-1]=="A":
            BA+=1
        elif tmp[0]=="B":
            B+=1
        elif tmp[-1]=="A":
            A+=1

if BA>0:
    if B>0 and A>0:
        total+=BA+1
        B-=1
        A-=1
    elif A>0:
        total+=BA
    elif B>0:
        total+=BA
    else:
        total+=BA-1
        
        
print(total+min(A,B))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat May 11 19:46:09 2019
divertaC
@author: maezawa
"""

n = int(input())
s = []
end_a = 0
begin_b = 0
b_to_a = 0
ab = 0
for _ in range(n):
    si = input()
    s.append(si)
    if si[-1] == 'A':
        end_a += 1
        if si[0] == 'B':
            b_to_a += 1
            end_a -= 1
    if si[0] == 'B':
        begin_b += 1
        if si[-1] == 'A':
            begin_b -= 1
    for i in range(len(si)-1):
        if si[i:i+2] == 'AB':
            ab += 1
cnt = ab 
if b_to_a > 0:
    cnt += b_to_a-1
    if end_a > 0:
        cnt += 1
        end_a -= 1
    if begin_b > 0:
        cnt += 1
        begin_b -= 1
cnt += min(end_a, begin_b)
print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
sl = [input() for _ in range(n)]
sb,la,cnt,both = 0,0,0,0
for s in sl:
  cnt += s.count("AB")
  if s[0] + s[-1] == "BA":
    both += 1
  elif s[0] == "B":
    sb += 1
  elif s[-1] == "A":
    la += 1
if both:
  cnt += both-1
  if la:
    cnt += 1
    la -= 1
  if sb:
    cnt += 1
    sb -= 1
print(cnt + min(la,sb))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())
fully_ab = 0
last_a = 0
head_b = 0
head_last_both = 0

for i in range(n):
    s = input().rstrip()
    fully_ab +=s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        head_last_both += 1
    elif s[0] == "B":
        head_b += 1
    elif s[-1] == "A":
        last_a += 1
    
assert (last_a+head_b+head_last_both <= n)
bigger = max(last_a,head_b)
lower  = min(last_a,head_b)
amari = bigger - lower

connected = max(0,head_last_both - 1)

ans1 = fully_ab
ans2 = lower + connected

if (amari>0 or lower > 0) and head_last_both > 0:
    ans2 += 1
print(ans1+ans2)

Submission status: Accepted

Solution code:
import re
N = int(input())

S = []
for i in range(N):
  S.append(input())

inner = 0
Bxxx = 0
xxxA = 0
BxxA = 0

pattern = re.compile(r'AB')

for s in S:
  mo = pattern.findall(s)
  inner += len(mo)
  if s[0] == "B" and s[-1] == "A":
    BxxA += 1
  elif s[0] == "B":
    Bxxx += 1
  elif s[-1] == "A":
    xxxA += 1
if BxxA > 0:
  total = inner + BxxA - 1
else:
  total = inner
if xxxA > 0 and BxxA > 0:
  total += 1
  xxxA -= 1
if Bxxx > 0 and BxxA > 0:
  total += 1
  Bxxx -= 1
total += min(xxxA, Bxxx)
print(total)

Submission status: Accepted

Solution code:
N = int(input())
S = [None] * N

count_AB = 0
right_A = 0
left_B = 0
right_A_left_B = 0

for i in range(N):
    s = input()
    count_AB += s.count('AB')
    if s[0] == "B" and s[-1] == "A":
        right_A_left_B += 1
    elif s[0] == "B":
        left_B += 1
    elif s[-1] == "A":
        right_A += 1

if right_A_left_B > 0:
    count_AB += (right_A_left_B - 1)
    right_A_left_B = 1
    # OK

if right_A_left_B == 0:
    min_AB = min(right_A, left_B)
    count_AB += min_AB
else:
    # right_A_left_B = 1
    if right_A == 0 or left_B == 0:
        if max(right_A, left_B) > 0:
            count_AB += 1
            right_A_left_B = 0
    else:
        count_AB += 1
        right_A_left_B = 0
        min_AB = min(right_A, left_B)
        count_AB += min_AB
print(count_AB)

Submission status: Accepted

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

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

Submission status: Accepted

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



def main(s):
    SB = []
    SBA = []
    SR = []
    for si in s:
        if si[0] == 'B':
            if si[-1] == 'A':
                SBA.append(si)
            else:
                SB.append(si)
        else:
            SR.append(si)
    if SR:
        R = [SR.pop()]
    elif SB:
        R = [SB.pop()]
    else:
        R = [SBA.pop()]
    SB.extend(SBA)
    while SR or SB:
        if SR and SB:
            if R[-1][-1] == 'A':
                R.append(SB.pop())
            else:
                R.append(SR.pop())
        elif SR:
            R.append(SR.pop())
        elif SB:
            R.append(SB.pop())
    return "".join(R)


print(main(s).count("AB"))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
n = int(input())
sl = [input() for _ in range(n)]

xa = []
bx = []
ba = []
x = []
for s in sl:
    if s[0]=="B" and s[-1]=="A":
        ba.append(s)
    elif s[-1]=="A":
        xa.append(s)
    elif s[0]=="B":
        bx.append(s)
    else:
        x.append(s)

if len(xa)>0:
    xa = xa[:-1]+[xa[-1]+"".join(ba)]
elif len(bx)>0:
    bx = bx[:-1]+["".join(ba)+bx[-1]]
else:
    x.append("".join(ba))

if len(xa)>=len(bx):
    for i in range(len(bx)):
        x.append(xa[i]+bx[i])
    x = x+xa[len(bx):]
else:
    for i in range(len(xa)):
        x.append(xa[i]+bx[i])
    x = x+bx[len(xa):]

res = "".join(x)
print(res.count("AB"))

Submission status: Accepted

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


def solve(n, ss):
    num_ab = sum(s.count("AB") for s in ss)
    num_both = sum(s[-1] == "A" and s[0] == "B" for s in ss)
    num_right_a = sum(s[-1] == "A" for s in ss) - num_both
    num_left_b = sum(s[0] == "B" for s in ss) - num_both
    # B --- A
    res = num_ab 
    if num_both > 0:
        res += num_both - 1
        if num_right_a > 0:
            num_right_a -= 1
            res += 1
        if num_left_b > 0:
            num_left_b -= 1
            res += 1
    # (X)B --- A(X)
    res += min(num_right_a, num_left_b)
    return res


def main():
    n = int(input())
    ss = [input() for _ in range(n)]
    res = solve(n, ss)
    print(res)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# N = int(input())
# A = [int(x) for x in input().split()]
# from collections import defaultdict
# dd = defaultdict(lambda: 0)

N = int(input())

S = []
bStart = 0
aEnd = 0
ba = 0
abSum = 0
for i in range(N):
    s = input()
    abSum += s.count('AB')

    if s[0] == 'B' and s[-1] == 'A':
        ba += 1
    elif s[0] == 'B':
        bStart += 1
    elif s[-1] == 'A':
        aEnd += 1

ret = 0

if ba > 0:
    ba -= 1
    if aEnd > 0:
        ba += 1
        aEnd -= 1
    if bStart > 0:
        ba += 1
        bStart -= 1

print(abSum + ba + min(bStart, aEnd))

Submission status: Accepted

Solution code:
from collections import defaultdict

N = int(input())
s = [input().strip() for _ in range(N)]

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

if h['BA'] > 0:
    ans += h['BA']-1
    if h['B'] > 0:
        ans += 1
        h['B'] -= 1
    if h['A'] > 0:
        ans += 1
        h['A'] -= 1

ans += min(h['B'], h['A'])

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for _ in range(N)]
a, b, ab = 0, 0, 0
ans = 0
for s in S:
    ans += s.count('AB')
    if s[-1] == 'A' or s[0] == 'B':
        ab += 1
    if s[-1] == 'A':
        a += 1
    if s[0] == 'B':
        b += 1
print(ans + min(a, b, max(ab-1, 0)))

Submission status: Accepted

Solution code:

N = int(input())
s = [input() for i in range(N)]

A = 0
B = 0
BA = 0
cnt = 0
for i in s:
    if i.startswith("B"):
        B += 1
    if i.endswith("A"):
        A += 1
    if i.startswith("B") and i.endswith("A"):
        BA += 1
    for j in range(1,len(i)):
        if i[j-1] + i[j] == "AB":
            cnt += 1

if BA == 0:
    cnt += min(A,B)
    print(cnt)
else:
    B -= BA
    A -= BA
    if A >= 1:
        cnt += 1
    if B >= 1:
        cnt += 1
    if A >= 2 and B >= 2:
        cnt += min(A-1,B-1)
    print(cnt + BA-1)

Submission status: Accepted

Solution code:
import re
n = int(input())
a = 0
b = 0
ab = 0
cnt = 0
for i in range(n):
    s = input()

    tmp = re.findall(r'AB',s)
    ab += len(tmp)

    if s[0] == "B":
        b += 1
    if s[-1] == "A":
        a += 1
    if s[0] == "B" and s[-1] == "A":
        cnt += 1 
if a == b and a == cnt and a > 0:
    print(a-1+ab)
else:
    print(min(a,b)+ab)

Submission status: Accepted

Solution code:
N = int(input())
cnt = 0
k = 0
l = 0
r = 0
for i in range(N) : 
    s = input()
    cnt += s.count("AB")
    if s[0] == "B" and s[len(s) - 1] == "A" : 
        k += 1
    elif s[0] == "B" : 
        l += 1
    elif s[len(s) - 1] == "A" : 
        r += 1
rst = cnt
if k == 0 : 
    rst += min(l , r)
elif k == 1 : 
    rst += min(1 , l)  + min(1 , r)  + max(min(l-1, r-1) , 0)
else : 
    rst += k - 1
    rst += min(1 , l)  + min(1 , r)  + max(min(l-1, r-1) , 0)
print(rst)

Submission status: Accepted

Solution code:
import sys, os

f = lambda:list(map(int,input().split()))
if 'local' in os.environ :
    sys.stdin = open('./input.txt', 'r')

def solve():
    n = f()[0]
    ans = 0
    cnt_only_head_b = 0
    cnt_only_end_a = 0
    cnt_headb_enda = 0
    for i in range(n):
        s = input()
        slen = len(s)
        for j in range(slen-1):
            if s[j:j+2] == 'AB':
                ans += 1
            
        if s[0] == 'B' and s[-1]!='A':
            cnt_only_head_b += 1
        if s[-1] == 'A' and s[0]!='B':
            cnt_only_end_a += 1
        if s[0] == 'B' and s[-1] == 'A':
            cnt_headb_enda += 1

    

    if cnt_headb_enda:
        ans += cnt_headb_enda - 1
        if cnt_only_end_a:
            ans += 1
            cnt_only_end_a -= 1
        if cnt_only_head_b:
            ans += 1
            cnt_only_head_b -= 1
        
        
    
    minab = min(cnt_only_end_a, cnt_only_head_b)
    ans += minab

    print(ans)


    
    

solve()

Submission status: Accepted

Solution code:
#Rs,Gs,Bs,Ns= input().split()
#R=int(Rs)
#G=int(Gs)
#B=int(Bs)
#N=int(Ns)
#ans=0
#sub_ans=0
#while(sub_ans>=N):

ans=0
f_a=0
b_b=0
a_b=0
str_list=[]
N= int(input())
for i in range(N):
    str=input()
    ans=ans+str.count("AB")
    if(str[-1]=="A"):
        f_a=f_a+1
    if(str[0]=="B"):
        b_b=b_b+1
    if(str[-1]=="A"and str[0]=="B"):
        a_b=a_b+1

if(f_a==N and b_b==N):
    ans=ans+N-1
elif((f_a==a_b)and(b_b==a_b)and(f_a!=0)):
    ans=ans+f_a-1
elif(f_a< b_b):
    ans=ans+f_a
else:
    ans=ans+b_b

#print(f_a)
#print(b_b)
print(ans)

Submission status: Accepted

Solution code:


def main():
    n = input()
    a = b = ab = s = 0
    for _ in xrange(n):
        st = raw_input()
        s += st.count('AB')
        if st.endswith('A'):
            if st.startswith('B'):
                ab += 1
            else:
                a += 1
        elif st.startswith('B'):
            b += 1
    if ab > 1:
        s += ab - 1
        ab = 1
    if ab and a:
        s += 1
        a -= 1
    if ab and b:
        s += 1
        b -= 1
    print s + min(a, b)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

N = int(input())
s_li = []
for _ in range(N):
    s_li.append(input().strip())

last_is_A = 0
first_is_B = 0
both_conditions_are_true = 0
AB_counter = 0
for i in s_li:
    if i[-1] == 'A': last_is_A += 1
    if i[0] == 'B': first_is_B += 1
    if i[-1] == 'A' and i[0] == 'B': both_conditions_are_true += 1
    AB_counter += i.count('AB')

if both_conditions_are_true == last_is_A == first_is_B == 0:
    print(AB_counter + min(last_is_A, first_is_B, N-1))
elif both_conditions_are_true == last_is_A == first_is_B:
    print(AB_counter + min(last_is_A, first_is_B, N-1, both_conditions_are_true-1))
else:
    print(AB_counter + min(last_is_A, first_is_B, N-1))

Submission status: Accepted

Solution code:
N = int(input())
s = []
ans = 0
numa = 0
numb = 0
numab = 0
for _ in range(N):
    s = input()
    num = 0
    for x,y in zip(s, s[1:]):
        if x == 'A' and y == 'B' :
            num += 1
    ans += num
    if s[0] == 'B' and s[-1] == 'A':
        numab += 1
    elif s[0] == 'B':
        numb += 1
    elif s[-1] == 'A':
        numa += 1
if numab == 0:
    print(ans + min(numa, numb))
else:
    if numa == 0 and numb == 0:
        print(ans + (numab-1))
    elif numa == 0:
        if numb == 0:
            print(ans + (numab-1))
        else:
            print(ans + (numab-1) + 1)
    elif numb == 0:
        if numa != 0:
            print(ans + (numab-1) + 1)
    else:
        print(ans + (numab-1) + 2 + min(numa-1,numb-1))

Submission status: Accepted

Solution code:
from sys import stdin
import numpy as np
 
N = int(input())
S = [input() for _ in range(N)]

cnt_innerAB = 0
cnt_endA_firstB = 0
cnt_endA = 0
cnt_firstB = 0

for i in range(N):
  cnt_innerAB += S[i].count('AB')
  if S[i][-1] == 'A' and S[i][0] == 'B':
    cnt_endA_firstB += 1
  if S[i][-1] == 'A' and S[i][0] != 'B':
    cnt_endA += 1
  if S[i][-1] != 'A' and S[i][0] == 'B':
    cnt_firstB += 1

if cnt_endA_firstB > 0 and cnt_endA == 0 and cnt_firstB == 0:
  cnt_sideAB = cnt_endA_firstB - 1
else:
  cnt_sideAB = min(min(cnt_endA, cnt_firstB) + cnt_endA_firstB, N-1)
ans = int(cnt_innerAB + cnt_sideAB)

print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
s = []
for _ in range(N):
    s.append(input()[:-1])

count_a = 0
count_b = 0
count_ab = 0
find_ab = 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":
            find_ab += 1

    if s[i][-1] == "A" and s[i][0] == "B":
        count_ab += 1
    elif s[i][-1] == "A":
        count_a += 1
    elif s[i][0] == "B":
        count_b += 1

max_ab = max(count_a, count_b)
min_ab = min(count_a, count_b)
counts = 0
if max_ab > 0:
    counts = count_ab
else:
    counts = max(count_ab-1, 0)
counts += min_ab

print(counts+find_ab)

Submission status: Accepted

Solution code:
N = int(input())
S = [None] * N
ans = 0
first_b = 0
last_a = 0
both = 0
for i in range(N):
  S[i] = input()
  if (S[i][-1] == 'A' and S[i][0] == 'B'):
    both += 1
  else:
    if (S[i][-1] == 'A'):
      last_a += 1
    if (S[i][0] == 'B'):
      first_b += 1
  ans += S[i].count('AB')

if (both):
  ans += both - 1
  if (last_a):
    ans += 1
    last_a -= 1
  if (first_b):
    ans += 1
    first_b -= 1

ans = ans + (last_a + first_b - abs(last_a - first_b)) // 2
print(ans)

Submission status: Accepted

Solution code:
def solve(N, Ss):
    a = 0
    b = 0
    both = 0
    ans = 0
    for s in Ss:
        ans += s.count("AB")
        if s[-1] == "A" and s[0] == "B":
            both += 1
        else:
            if s[-1] == "A":
                a += 1
            if s[0] == "B":
                b += 1

    if both > 0:
        ans += both - 1

    if both > 0 and a > 0:
        ans += 1
        a -= 1

    if both > 0 and b > 0:
        ans += 1
        b -= 1

    a = min(N, a)
    b = min(N, b)
    ans += min(a, b)
    return ans

if __name__ == "__main__":
    N = int(input())
    Ss = [input() for _ in range(N)]
    print(solve(N, Ss))

Submission status: Accepted

Solution code:
N = int(input())
l,r,lr = 0,0,0
ans = 0
for i in range(N):
    s = input()
    if s[0] == "B" and s[-1] == "A":
        lr += 1
    elif s[0] == "B":
        l += 1
    elif s[-1] == "A":
        r += 1
    for j in range(len(s)-1):
        string = s[j]+s[j+1]
        if string == "AB":
            ans += 1
if lr > 0:
    ans += lr-1
    if l>0 and r>0:
        ans += 2
        l -= 1
        r -= 1
        ans += min(l,r)
    elif (r == 0 or l == 0) and not (r==l==0):
        ans += 1
else:
    ans += min(l,r)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
ans = 0
Bx = 0
BA = 0
xA = 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':
        Bx += 1
    elif s[-1] == 'A':
        xA += 1
if BA > 0:
    ans += (BA - 1)
    if Bx > 0:
        ans += 1
        Bx -= 1
    if xA > 0:
        ans += 1
        xA -= 1
ans += min(Bx, xA)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
ans = 0
A,B,AB = 0,0,0
for i in range(N):
    s = 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


add =  0

if AB != 0:
    add += (AB - 1)
    if A >= 1:
        A -= 1
        add += 1
    if B >= 1:
        B -= 1
        add += 1
add += min(A,B)

print(min(add,N-1) + ans)

Submission status: Accepted

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

IB= [0] * (N)
LA = [0] * (N)
flag = True
Eflag = False
cntb= 0
cnta = 0
ans = 0
for i in range(N):
    if S[i][0] == 'B':
        IB[i] = 1
        cntb += 1
    if S[i][len(S[i])-1] == 'A' :
        LA[i] = 1
        cnta += 1
    if (IB[i] == 1 and LA[i] == 0) or (IB[i]==0 and LA[i] == 1):
        flag = False
    elif (IB[i] == 1 and LA[i] == 1):
        Eflag = True
    for j in range(len(S[i])-1):
        if S[i][j] == 'A' and S[i][j+1]=='B' : ans += 1
        
        
ans += min(cntb,cnta)
if Eflag and flag:    
    ans -= 1



print(ans)

Submission status: Accepted

Solution code:
n=int(input())
count_list=[]
b_a=0
b=0
a=0

for i in range(n):
    s=input()
    length=len(s)
    if s[0]=="B" and s[length-1]=="A":
        b_a=b_a+1
    if s[0]=="B":
        b=b+1
    if s[length-1]=="A":
        a=a+1
    count_list.append(s.count("AB"))
a=a-b_a
b=b-b_a
minimum=min(a+b_a, b+b_a)
if b==0 and a==0 and b_a==0:
    print(sum(count_list))
elif b==0 and a==0:
    print(sum(count_list)+minimum-1)
else:
    print(sum(count_list)+minimum)

Submission status: Accepted

Solution code:
n=int(input())
l=[input() for i in range(n)]
ct=0;cta=0;ctb=0;ctab=0
for i in range(len(l)):
  for j in range(len(l[i])-1):
    if l[i][j]=='A' and l[i][j+1]=='B':ct+=1
  if l[i][0]=='B' and l[i][len(l[i])-1]=='A':
    ctab+=1
    cta+=1
    ctb+=1
  elif l[i][len(l[i])-1]=='A':cta+=1
  elif l[i][0]=='B':ctb+=1
x=min(cta,ctb)

if ctab==cta and ctab==ctb and ctab!=0:
  print(ct+x-1)
else:
  print(ct+x)

Submission status: Accepted

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

res = 0
bx = 0
xa = 0
ba = 0
for i in range(n):
    res += s[i].count('AB')
    if s[i][0] == 'B' and s[i][-1] == 'A':
        ba += 1
    elif s[i][0] == 'B':
        bx += 1
    elif s[i][-1] == 'A':
        xa += 1
if ba>0:
    res += ba-1
    if xa > 0:
        res += 1
        xa -= 1
    if bx > 0:
        res += 1
        bx -= 1
res += min(xa, bx)
print(res)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

N = int(input())
S = [input() for i in range(N)]

ans = sum([s.count('AB') for s in S])
count_A = 0
count_B = 0
count_AB = 0
for s in S:
    if s[0] == 'B':
        count_B += 1
        if s[-1] == 'A':
            count_AB += 1
    if s[-1] == 'A':
        count_A += 1

if max(count_A, count_B) != 0 and max(count_A, count_B) == count_AB:
    ans += count_AB-1
else:
    ans += min(count_A, count_B)

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())
cnt,ext,na,nb,nc = 0,0,0,0,0
for i in range(N):
    s = input()
    cnt += s.count('AB')
    if (s[-1] == 'A') and (s[0]!='B'):
        na += 1
    if (s[-1] != 'A') and (s[0]=='B'):
        nb += 1
    if(s[-1] == 'A') and (s[0]=='B'):
        nc += 1

if nc>0:
    ext += nc-1
    if na>0:
        ext += 1
        na -= 1
    if nb>0:
        ext += 1
        nb -= 1

ext += min(na,nb)

print(cnt+ext)

Submission status: Accepted

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

k = sum(t.count('AB') for t in s)
ab = sum(t[-1] == 'A' and t[0] == 'B' for t in s)
a = sum(t[-1] == 'A' and t[0] != 'B' for t in s)
b = sum(t[-1] != 'A' and t[0] == 'B' for t in s)
ans = k
isA = False
if a > 0:
    a -= 1
    isA = True
if ab > 0:
    if isA:
        ans += ab
    else:
        ans += ab - 1
    isA = True
if isA:
    if b > 0:
        ans += 1
        b -= 1
    ans += min(a, b)
else:
    ans += min(a, b)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
last_a = 0
start_b = 0
sl_ba = 0
for i in range(n):
    s = input()
    ans += s.count("AB")
    if s.rfind("A") == len(s) - 1:
        last_a += 1
    if s.find("B") == 0:
        start_b += 1
    if s.find("B") == 0 and s.rfind("A") == len(s) - 1:
        sl_ba += 1
ans += min(last_a, start_b)
if sl_ba >= 2 and last_a == sl_ba and start_b == sl_ba:
    ans -= 1
print(ans)

Submission status: Accepted

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

ans = cnt_b = cnt_a = cnt_ba = 0
for s in S:
    ans += s.count("AB")
    if s[0] == "B":
        cnt_b += 1
    if s[-1] == "A":
        cnt_a += 1
    if s[0] == "B" and s[-1] == "A":
        cnt_ba += 1

if cnt_a == cnt_ba and cnt_b == cnt_ba:
    cnt_a -= 1
    cnt_b -= 1
ans += max(min(cnt_a, cnt_b, N - 1), 0)

print(ans)

Submission status: Accepted

Solution code:
from collections import*
n,*s=open(0).read().split()

d=defaultdict(int)
#print(s)
ans=0
for i in s:
    ans+=i.count("AB")
    if i[0]=="B" or i[-1]=="A":
        d[(i[0]=="B",i[-1]=="A")]+=1
#print(d,ans)
if len(d.values())==0:
    print(ans)
    exit()
else:
    if d[(True,True)]>0 and d[(True,False)]>0 and d[(False,True)]>0:  #ABggfgAB
        ans+=d[(True,True)]+1
        d[(True,True)]=0
        d[(True,False)]-=1 
        d[(False,True)]-=1
#        print(d,ans)
    if d[(True,True)]>0 and d[(True,False)]>0:
#        print(d)
        ans+=d[(True,True)]
        d[(True,True)]=0
        d[(True,False)]-=1
    if d[(True,True)]>0 and d[(False,True)]>0:
#        print(d)
        ans+=d[(True,True)]
        d[(True,True)]=0
        d[(False,True)]-=1
    if d[(True,True)]>1:
        ans+=d[(True,True)]-1
    if d[(False,True)]>0 and d[(True,False)]>0:
#        print(d)
        ans+=min(d[(False,True)],d[(True,False)])
print(ans)