Problem:


Score : 400 points

Problem Statement

Snuke has N strings. The i-th string is s_i.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4



Sample input:
3
ABCA
XBAZ
BAD


Sample output:
2

Submission status: Accepted

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

count = 0
for i in range(n):
    for j in range(len(s[i])-1):
        if s[i][j:j+2] == "AB":
            count += 1
a_end = 0
b_start = 0
both = 0
for i in range(n):
    if s[i][0] == "B":
        if s[i][-1] == "A":
            both += 1
        else:
            b_start += 1
    elif s[i][-1] == "A":
        a_end += 1
if a_end == 0 and b_start == 0:
    count += max(0,(both-1))
else:
    count += (both + min(a_end, b_start))
print(count)

Submission status: Accepted

Solution code:
n=int(input())
s=[input() for i in range(n)]
b_b=0
e_a=0
ba=0
ab=0
for i in range(n):
    for j in range(len(s[i])-1):
        if s[i][j:j+2]=='AB':
            ab+=1
    if s[i][0]=='B' and s[i][-1]=='A':
        ba+=1
    elif s[i][0]=='B':
        b_b+=1
    elif s[i][-1]=='A':
        e_a+=1
if ba>0:
    ab+=ba-1
    if e_a>0:
        b_b+=1
    if b_b>0:
        e_a+=1
print(ab+min(b_b,e_a))

Submission status: Accepted

Solution code:
import math
N=int(input())
ans=0
a,b=0,0
tmp=0
for i in range(N):
    s=input()
    if s[0]=="B": b+=1
    if s[-1]=="A": a+=1
    if a!=b: tmp=1
    ans+=s.count("AB")


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

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for k in range(N)]
ans = 0
for s in S:
    ans += s.count("AB")


C = [[0,0] for k in range(N)]
for k in range(N):
    if S[k][0] == "B":
        C[k][1] = 1
    if S[k][-1] == "A":
        C[k][0] = 1
p = 0
q = 0
r = 0
for k in range(N):
    if C[k] == [0, 1]:
        p += 1
    elif C[k] == [1, 1]:
        q += 1
    elif C[k] == [1, 0]:
        r += 1
if p >= 1 and r >= 1 and q >= 1:
    print(ans + q+1 + min(p-1,r-1))
elif (p>=1 and r==0 and q>=1) or (p==0 and r>=1 and q>=1):
    print(ans + q)
elif p >= 1 and r >= 1 and q == 0:
    print(ans + min(p,r))
elif p == 0 and r == 0 and q >= 1:
    print(ans + q-1)
else:
    print(ans)

Submission status: Accepted

Solution code:
import sys
N = int(input())
S = [input() for _ in range(N)]
a = 0
b = 0
ans = 0
aru = False
zenaru = True
for s in S:
    TB = (s[0] == 'B')
    TA = (s[-1] == 'A')
    ans += s.count('AB')
    if TB:
        b += 1
        aru = True
    if TA:
        a += 1
        aru = True
    if TA ^ TB:
        zenaru = False
if a == 0 or b == 0:
    print(ans)
    sys.exit()
print(ans + min(a, b) - zenaru)

Submission status: Accepted

Solution code:
ans = 0
first_b = 0
last_a = 0
same = 0

N = int(input())

for i in range(N):
    s = input()
    ans += s.count("AB")
    if s[0] == "B":
        first_b += 1
    if s[-1] == "A":
        last_a += 1
    if s[0] == "B" and s[-1] == "A":
        same +=1

ans += min(first_b, last_a)
if same > 0 and first_b ==  last_a and first_b == same:
    ans -=1
print(ans)

Submission status: Accepted

Solution code:
n=int(input())

a=0
b=0
ab=0
flag=0

for i in range(n):
    line=input()
    if flag!=1 and (line[len(line)-1]!='A' and line[0]=='B') or (line[len(line)-1]=='A' and line[0]!='B'):
        flag=1
    if line[0]=='B':
        b=b+1
    if line[len(line)-1]=='A':
        a=a+1
    for j in range(len(line)-1):
        if line[j]=='A' and line[j+1]=='B':
            ab=ab+1

if flag==0 and a!=0 and b!=0:
    a,b=a-1,b-1

if b>a:
    print(ab+a)
else:
    print(ab+b)

Submission status: Accepted

Solution code:
N = int(input())

s = ["" for i in range(N)]
B = 0
A = 0
BA = 0

score = 0
for i in range(N):
    s[i] = input()
    if s[i][0] == "B" and s[i][-1] != "A":
        B += 1
    if s[i][0] != "B" and s[i][-1] == "A":
        A += 1
    if s[i][0] == "B" and s[i][-1] == "A":
        BA += 1
    for j in range(len(s[i])-1):
        if s[i][j] == "A" and s[i][j+1] == "B":
            score += 1

if BA >= 1:
    score += BA - 1
    if A >= 1 and B >= 1:
        score += 2
        A -= 1
        B -= 1
    if A >= 1 and B == 0:
        score += 1
    if A == 0 and B >= 1:
        score += 1

print(score + min(A,B))

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for i in range(N)]
#print(S)
a_cnt = 0
b_cnt = 0
ab_cnt = 0
b_a_cnt = 0
for i,s in enumerate(S):
    ab_cnt += s.count("AB")
    if s[-1] == "A":
        a_cnt += 1
    if s[0] == "B":
        b_cnt += 1
    if s[0] == "B" and s[-1] == "A":
        b_a_cnt += 1
if a_cnt == b_cnt == b_a_cnt and b_a_cnt != 0:
    ab_cnt += min(a_cnt, b_cnt) - 1
else:
    ab_cnt += min(a_cnt, b_cnt)

print(ab_cnt)

Submission status: Accepted

Solution code:
N = int(input())

ans = 0
b_ = 0
_a = 0
b_a = 0

for _ 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:
    ans += b_a - 1
    if 0 < _a >= b_:
        ans += 1
        _a -= 1
    if 0 < b_ >= _a:
        ans += 1
        b_ -= 1
ans += min(_a, b_)
    


print(ans)

Submission status: Accepted

Solution code:
N = int(input())
n=0
a_tail = b_head = both = 0
for _ in range(N):
    s = input()
    n += s.count('AB')

    if s[-1]=='A' and s[0]=='B':
        both += 1
    elif s[-1]=='A':
        a_tail += 1
    elif s[0]=='B':
        b_head += 1

if a_tail==0 and b_head==0:
    if both==0:
        print(n)
    else:
        print(n+both-1)
else:
    print(n+min(a_tail,b_head)+both)

Submission status: Accepted

Solution code:
import sys
import re

N = int(sys.stdin.readline().strip())
start_b = 0
end_a = 0
both = 0
contains = 0

for _ in range(N):
    line = sys.stdin.readline().strip()
    pattern = r"AB"
    matchedList = re.findall(pattern, line)
    
    #if line.find("AB") != -1:
    contains += len(list(matchedList))
    if line[0] == "B" and line[-1] == "A":
        both += 1
    elif line[0] == "B":
        start_b += 1
    elif line[-1] == "A":
        end_a += 1

count = contains
count += max(0, both-1)

if both == 0:
    count += min(end_a, start_b)
elif end_a != 0 and start_b != 0:
    count += 2
    count += min(end_a-1, start_b-1)
elif not (end_a == 0 and start_b == 0):
    count += 1
print(count)

Submission status: Accepted

Solution code:
n = int(input())
ary = []
ans = 0
final_a = 0
start_b = 0
ab = 0
for i in range(n):
  s = input()
  ary.append(s)
  if s[0] == "B" and s[-1] == "A":
    ab += 1
  else:
    if s[0] == "B":
      start_b += 1
    if s[-1] == "A":
      final_a += 1
  while True:
    idx = s.find("AB")
    if idx == -1:
      break
    else:
      s = s[idx+2:]
      ans += 1

if ab > 0:
  ans += ab - 1
  if start_b > 0:
    ans += 1
    start_b -= 1
  if final_a > 0:
    ans += 1
    final_a -= 1

if start_b >= final_a:
  ans += final_a
else:
  ans += start_b
print(ans)

Submission status: Accepted

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

count = 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


a = 0
b = 0
ba = 0

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

if ba == 0:
    count += min(a, b)
else:
    if ba > 1:
        count += ba - 1
    if a > 0:
        a -= 1
        count += 1
    if b > 0:
        b -= 1
        count += 1
    count += min(a, b)

print(count)

Submission status: Accepted

Solution code:
N = int(input())
A = 0
B = 0
BA = 0
num = 0
for i in range(N):
    k = input()
    if k[0] == 'B' and k[-1] == 'A':
        BA += 1
    elif k[0] == 'B':
        B += 1
    elif k[-1] == 'A':
        A += 1

    for j in range(len(k) - 1):
        if k[j:j + 2] == 'AB':
            num += 1

num += max(0, BA - 1)
BA -= max(0, BA - 1)
num += min(BA, A) + min(BA, B)
A -= min(BA, A)
B -= min(BA, B)
num += min(A, B)
print(num)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    S = [input() for _ in range(N)]
    ans = 0
    bxa = 0
    bx = 0
    xa = 0
    for s in S:
        ans += s.count("AB")
        if s.startswith("B") and s.endswith("A"):
            bxa += 1
        elif s.startswith("B"):
            bx += 1
        elif s.endswith("A"):
            xa += 1

    ans += min(bx, xa)
    if bxa >= 1:
        ans += bxa - (1 if max(bx, xa) == 0 else 0)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# /usr/bin/python
# -*- coding: utf-8 -*-
import sys

N = int(input())
ret = 0
pat = [0,0,0,0]
## pat:=[--, B-, -A, BA]

for _ in range(N):
  s = str(input())
  ret += s.count("AB")
  p = 0
  if s[0]=='B':
    p += 1
  if s[-1]=='A':
    p += 2
  pat[p] += 1

ret += max(0, pat[3]-1)
if pat[1]>0 and pat[3]>0:
  ret += 1
  pat[1]-=1
if pat[2]>0 and pat[3]>0:
  ret += 1
  pat[2]-=1
ret += min(pat[1],pat[2])

print(ret)

Submission status: Accepted

Solution code:
N=int(input())
numca=0
numbc=0
numba=0
ans=0
for i in range(N):
    s=input()
    for j in range(len(s)):
        if j==0 and s[j]=="B":
            numbc+=1
        elif j==len(s)-1 and s[j]=="A":
            numca+=1
        elif j!=len(s)-1 and s[j]=="A" and s[j+1]=="B":
            ans+=1
    if s[0]=="B" and s[-1]=="A":
        numbc-=1
        numca-=1
        numba+=1
if numba==0:
    print(ans+min(numbc,numca))
    quit()
ans+=numba-1
if numbc==0 and numca==0:
    print(ans)
    quit()
if numbc==0 or numca==0:
    print(ans+1)
    quit()
ans+=min(numbc+1,numca+1)
print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque, OrderedDict
from copy import deepcopy
from fractions import gcd
from functools import lru_cache, reduce
from math import ceil, floor
from sys import setrecursionlimit

import heapq as hq
import itertools as its
import operator as op


# globals
inf = float('inf')
N = 0


def set_inputs():
    global N
    return


def main():
    setrecursionlimit(100000)
    set_inputs()
    # ----------MAIN----------
    n = get_int()
    s = get_data(n, [str])
    ans = 0
    a = 0
    b = 0
    ba = 0
    for si in s:
        if si[-1] == 'A':
            a += 1
        if si[0] == 'B':
            b += 1
        if si[-1] == 'A' and si[0] == 'B':
            ba += 1
        for c1, c2 in zip(si, si[1:]):
            if c1 == 'A' and c2 == 'B':
                ans += 1
    if ba != a or ba != b or ba == 0:
        ans += min(a, b)
    else:
        ans += ba - 1
    print(ans)
    return


def get_int():
    return int(input())


def get_float():
    return float(input())


def get_str():
    return input().strip()


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


def get_lf():
    return [float(f) for f in input().split()]


def get_lc():
    return list(input().strip())


def get_data(n, types, sep=None):
    if len(types) == 1:
        return [types[0](input().strip()) for _ in range(n)]
    return list(zip(*(
        [t(x) for t, x in zip(types, input().strip().split(sep=sep))]
        for _ in range(n)
    )))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

N = int(input())

tmp = [0,0,0]
ans = 0
for i in range(N):
    s = input()
    ans += s.count("AB")
    if s.endswith("A") and s.startswith("B"):
        tmp[0] += 1
    elif s.endswith("A"):
        tmp[1] += 1
    elif s.startswith("B"):
        tmp[2] += 1


if tmp[0] > 0:
    ans += tmp[0] - 1

    if tmp[1] > 0:
        ans += 1
        tmp[1] -= 1

    if tmp[2] > 0:
        ans += 1
        tmp[2] -= 1

ans += min(tmp[1], tmp[2])
print(ans)

Submission status: Accepted

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

# 各文字列中のABの個数をカウント
L = [0 for i in range(N)]
for i in range(N):
    l = len(S[i])
    count = 0
    for j in range(l-1):
        if S[i][j] == 'A' and S[i][j+1] == 'B':
            count += 1
    L[i] = count

# a = 'B...A', b = 'B...notA', c = 'notB...A'
a, b, c = 0, 0, 0
for i in range(N):
    l = len(S[i])
    if S[i][0] == 'B' and S[i][l-1] == 'A':
        a += 1
    elif S[i][0] == 'B':
        b += 1
    elif S[i][l-1] == 'A':
        c += 1

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

Submission status: Accepted

Solution code:
N=int(input())
ans=0
Aend=0
Bstart=0
AB=0
for _ in range(N):
  s=input()
  ans+=s.count('AB')
  if s[-1]=='A' and s[0]=='B':
    AB+=1
  elif s[-1]=='A':
    Aend+=1
  elif s[0]=='B':
    Bstart+=1
if Aend==0 and Bstart==0 and AB>0:
  print(ans+AB-1)
  exit()
print(ans+min(Aend+AB,Bstart+AB))

Submission status: Accepted

Solution code:
N = int(input())
ab_count = 0
heading_b_count = 0
trailing_a_count = 0
both_sides_count = 0
for _ in range(N):
    s = input()
    ab_count += s.count('AB')
    if s[0] == 'B':
        heading_b_count += 1
    if s[-1] == 'A':
        trailing_a_count += 1
    if s[0] == 'B' and s[-1] == 'A':
        both_sides_count += 1

ans = ab_count + min(heading_b_count, trailing_a_count)
if both_sides_count == trailing_a_count and both_sides_count == heading_b_count and both_sides_count > 0:
    ans -= 1
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
s=[input() for _ in range(n)]
cnt=0
cnt_xa=0
cnt_bx=0
cnt_ba=0
for i in range(n):
    cnt += s[i].count('AB')
    if s[i][-1] == 'A' and s[i][0] != 'B':
        cnt_xa += 1
    elif s[i][0] == 'B' and s[i][-1] != 'A':
        cnt_bx += 1
    elif s[i][-1] == 'A' and s[i][0] == 'B':
        cnt_ba += 1
    else: continue
if cnt_xa==0:
    if cnt_ba>0:
        cnt_xa=1
        cnt_ba-=1
if cnt_bx==0:
    if cnt_ba>0:
        cnt_bx=1
        cnt_ba-=1
cnt += cnt_ba
cnt += min(cnt_xa,cnt_bx)
print(cnt)

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
back = 0
front = 0
either = 0
for i in range(n):
  s = str(input())
  ans += s.count("AB")
  if s[-1] == "A" and s[0] == "B":
    either += 1
  else:
    if s[-1] == "A":
      back += 1
    if s[0] == "B":
      front += 1

if front == back == 0:
  either = max(0, either - 1)
back += either
front += either
print(ans + min(back, front))

Submission status: Accepted

Solution code:
N = int(input())
s = [input() for _ in [0]*N]
ni = [0]*N
for i,si in enumerate(s):
    for j,c in enumerate(si[:-1]):
        if c == "A" and si[j+1] == "B":
            ni[i] += 1
cntA,cntB,cntAB = 0,0,0
for si in s:
    if si[0]=="B" and si[-1]=="A":
        cntAB += 1
    elif si[0]=="B":
        cntB += 1
    elif si[-1]=="A":
        cntA += 1
ans = sum(ni) + max(0,cntAB - (cntA==0 and cntB==0)) + min(cntA,cntB)
print(ans)

Submission status: Accepted

Solution code:
#C問題
N=int(input())
B=0
A=0
BA=0
count=0
for i in range(N):
    s=str(input())
    slist=list(s)
    slen=len(slist)
    flag=0
    abflag=0
    j=0
    for j in range(slen):
        if j == 0:
            if slist[0] == "B":
                flag=1
            elif slist[0] == "A":
                abflag=1
            else:
                pass
        elif j == slen-1:
            if slist[-1] == "A":
                if flag == 1:
                    flag=3
                else:
                    flag=2
            elif slist[-1] == "B":
                if abflag==1:
                    count+=1
            else:
                pass
        else:
            if slist[j] == "A":
                abflag=1
            elif slist[j] == "B":
                if abflag==1:
                    count+=1
                    abflag=0
                else:
                    abflag=0
            else:
                abflag=0
                
    if flag == 1:
        B+=1
    elif flag == 2:
        A+=1
    elif flag == 3:
        BA+=1
        
if BA>=1:
    count+=(BA-1)

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

Submission status: Accepted

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

c+=min(a,b)
k = min(a,b)
a = a-k
b = b-k
if s!=0:
    s = s-1
    c+=s
    if a!=0 or b!=0 or k!=0:
        c+=1
    
print(c)

Submission status: Accepted

Solution code:
X=[input() for _ in range(int(input()))]
a,b,e,s=0,0,0,0
for x in X:
	a += x.count("AB")
	if x.endswith("A") and x.startswith("B"):
		b += 1
	elif x.endswith("A"):
		e += 1
	elif x.startswith("B"):
		s += 1
if b > 0:
	a += b-1
	if e > 0:
		e -= 1
		a += 1
	if s > 0:
		s -= 1
		a += 1
a += min(e,s)
print(a)

Submission status: Accepted

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

base = 0
for i in range(n):
    tar = a[i]
    for k in range(0,len(tar)-1):
        if tar[k:k+2] == "AB":
            base += 1


fir_b = []
las_a = []
b_a = []
for i in range(n):
    tar = a[i]
    if tar[0] == "B" and tar[-1] == "A":
        b_a.append(i)
    elif tar[0] == "B":
        fir_b.append(i)
    elif tar[-1] == "A":
        las_a.append(i)


addi = 0
if len(b_a) == 0:
    addi += min(len(fir_b),len(las_a))
else:
    addi += len(b_a)-1
    if len(las_a) > 0 and len(fir_b) >0:
        addi += 2+ min(len(fir_b),len(las_a))-1
    elif len(las_a) == 0 and len(fir_b) >0:
        addi += 1
    elif len(las_a) > 0 and len(fir_b) == 0:
        addi += 1


print(addi+base)

Submission status: Accepted

Solution code:
n=int(input())
cnt=0
cnta=0
cntb=0
cntba=0
for i in range(n):
    s=input()
    for i in range(1,len(s)):
        if s[i]=='B' and s[i-1]=='A':
            cnt+=1
    if s[-1]=='A' and s[0]=='B':
        cntba+=1
    elif s[-1]=="A":
        cnta+=1
    elif s[0]=="B":
        cntb+=1
#print(cnt,cnta,cntb,cntba)
if cntb==0 and cntba==0:
    print(cnt)
elif cntb==0 and cntba!=0:
    print(cnt+min(cntba+cntb,cntba+cnta-1))
else:
    print(cnt+min(cntb+cntba,cnta+cntba))

Submission status: Accepted

Solution code:
N = int(input())
ans = 0
g = [0,0,0]

for i in range(N):
    S = input()
    if 'AB' in S:
        ans += S.count('AB')
    if S[0] == 'B' and S[-1] == 'A':
        g[0] += 1
    elif S[0] == 'B':
        g[1] += 1
    elif S[-1] == 'A':
        g[2] += 1

if g[1]==0 and g[2]==0 and g[0]!=0:
    ans += g[0] - 1
else:
    ans += min(g[1],g[2]) + g[0]

print(ans)

Submission status: Accepted

Solution code:
N = int(input())

num_a = 0
num_b = 0
ab = 0
count = 0

for i in range(N):
    s = input()
    if s[0] == 'B':
        num_b += 1
    
    if s[-1] == 'A':
        num_a += 1
    
    if s[0] == 'B' and s[-1] == 'A':
        count += 1
    
    ab += s.count('AB')

if num_a == num_b and num_a == count:
    if count == 0:
        print(ab)
    else:
        print(ab + num_a - 1)
else:
    if num_a >= num_b:
        print(ab + num_b)
    
    else:
        print(ab + num_a)

Submission status: Accepted

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

count_AB = [s[i].count("AB") for i in range(N)]

headB = 0
tailA = 0
headB_and_tailA = 0
for i in range(N):
    #print("i =", i)
    if s[i][0] == 'B':
        if s[i][-1] != 'A':
            #print("headB")
            headB += 1
        else:
            headB_and_tailA += 1
            #print("both")
    elif s[i][-1] == 'A':
        tailA += 1
        #print("tailA")

"""
print("both =", headB_and_tailA)
print("headB = ", headB)
print("tailA = ", tailA)
"""
result = sum(count_AB) + min(headB, tailA)
headB -= min(headB, tailA)
tailA -= min(headB, tailA)
for _ in range(headB_and_tailA):
    if tailA > 0:
        result += 1
    elif headB > 0:
        result += 1
    else:
        tailA += 1
#print("sum = ", sum(count_AB))
    
print(result)

Submission status: Accepted

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

Submission status: Accepted

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


def solve(N: int, S: "List[str]"):
    ret = 0
    a = 0
    b = 0
    ab = 0
    for s in S:
        i = 0
        for i in range(len(s) - 1):
            if s[i:i+2] == 'AB':
                ret += 1
        if s[0] == 'B':
            a += 1
        if s[-1] == 'A':
            b += 1
        if s[0] == 'B' and s[-1] == 'A':
            ab += 1
    ret += min(a, b)
    if a > 0 and a == b and a == ab:
        ret -= 1
    print(ret)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    s = [ next(tokens) for _ in range(N) ]  # type: "List[str]"
    solve(N, s)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

n = int(input())
t = [0]
for i in range(n):
    t.append(list(input()))
del t[0]

a = 0
b = 0
ab = 0
ba = 0
for i in range(n):
    temp = "".join(t[i])
    ab += temp.count("AB")
    if t[i][-1] == "A" and t[i][0] == "B":
        ba += 1
    elif t[i][0] == "B":
        b += 1
    elif t[i][-1] == "A":
        a += 1

if a == 0 and b == 0:
    temp = max(0,ba - 1)
else:
    temp = min(a,b) + ba

print(ab + temp)

Submission status: Accepted

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

Submission status: Accepted

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

# in
cnt = [0] * N
for i, si in enumerate(s):
    tmp = 0
    for j in range(len(s[i]) - 1):
        if si[j] == 'A' and si[j + 1] == 'B':
            tmp += 1
    cnt[i] = tmp
# print("#", cnt)
    
# edge
As = 0
Bs = 0
ABs = 0
for i, si in enumerate(s):
    if si[-1] == 'A' and si[0] == 'B':
        ABs += 1
    elif si[-1] == 'A':
        As += 1
    elif si[0] == 'B':
        Bs += 1
# print("#", As, Bs, ABs)
        
ans = 0

# chain of B*A
if ABs > 0:
    ans += max(0, (ABs - 1))
    # edge
    if As > 0:
        ans += 1
        As -= 1
    if Bs > 0:
        ans += 1
        Bs -= 1
    
# left pairs
ans += min(As, Bs) 

print(sum(cnt) + ans)

Submission status: Accepted

Solution code:
import sys
from operator import itemgetter
from collections import deque
sys.setrecursionlimit(10*5)

ans=0
p,q,r=0,0,0
n=int(input())
s=[]
for i in range(n):
    a=input()
    st=a[0]
    ed=a[-1]
    ans+=a.count('AB')
    if st=='B' and ed=='A':
        p+=1
    elif ed=='A':
        q+=1
    elif st=='B':
        r+=1
if q>0 and r>0:
    ans+=max(0, p+1+min(q-1,r-1) )
elif q==0:
    ans+=max(0, p-1 +(1 if r>0 else 0) )
elif r==0:
    ans+=max(0, p-1 +(1 if q>0 else 0) )
    
print(ans)

Submission status: Accepted

Solution code:
flag = True

N = int(input())
S = list()

ans = 0
a_end = 0
b_start = 0

for i in range(N):

    s = input()

    ans += s.count("AB")

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

        if flag and s[-1] != 'A':
            flag = False

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

        if flag and s[0] != 'B':
            flag = False

ans += min(a_end, b_start)

if flag and a_end != 0:
    ans -= 1

print(ans)

Submission status: Accepted

Solution code:
N=int(input())
ans=0
A=0
BA=0
B=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":
            ans+=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
#print(ans,A,B,BA)
if A>=1 or B>=1:
    print(ans+BA+min(A,B))
elif BA>=1:
    print(ans+BA-1)
else:
    print(ans)

Submission status: Accepted

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

ans = 0
_A = 0
B_ = 0
B_A = 0

for s in S:
    for i in range(len(S)-1):
        if s[i:i+2] == "AB":
            ans += 1
    if s[0] == "B" and s[-1] == "A":
        B_A += 1
    elif s[0] == "B":
        B_ += 1
    elif s[-1] == "A":
        _A += 1

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

if B_A==1 and B_>0:
    ans += 1
    B_A -= 1

if B_A==1 and _A>0:
    ans += 1
    B_A -= 1

if _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())
S=[input().strip() for i in range(N)]

ANS=0
for s in S:
    ANS+=s.count("AB")


_A=0
B_=0
BA=0

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


#print(ANS,_A,B_,BA)

if _A!=0 or B_!=0:
    print(ANS+BA+min(_A,B_))

else:
    if BA!=0:
        print(ANS+BA-1)
    else:
        print(ANS+BA)

Submission status: Accepted

Solution code:
def s(generator, splitter, mapper):
    return [ mapper(s) for s in generator().split(splitter) ]

# スペース区切りの入力を読み込んで数値リストにして返します。
def get_nums_l():
    return [ int(s) for s in input().split(" ")]

# 改行区切りの入力をn行読み込んで数値リストにして返します。
def get_nums_n(n):
    return [ int(input()) for _ in range(n)]

n = int(input())

strs = [ input() for _ in range(n) ]

ab = sum(map(lambda s:s.count("AB"), strs))
# print(ab)

last_a = sum(map(lambda s:1 if s.endswith("A") else 0, strs))

first_b = sum(map(lambda s:1 if s.startswith("B") else 0, strs))

both = sum(map(lambda s:1 if s.endswith("A") and s.startswith("B") else 0, strs))

if both > 0 and last_a == first_b and first_b == both:
    print(ab + min(last_a, first_b) - 1)
else:
    print(ab + min(last_a, first_b))

Submission status: Accepted

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

count = 0
countA = 0
countB = 0
countAB = 0

for each_s in S:
    if each_s[0] == "B" and each_s[-1] == "A":
        countAB += 1
    else:
        if each_s[0] == "B":
            countB += 1
        elif each_s[-1] == "A":
            countA += 1
    count += each_s.count("AB")

if countAB >= 1:
    count += countAB - 1
    if countA > 0:
        count += 1
        countA -= 1
    if countB > 0:
        count += 1
        countB -= 1
    count += min(countA, countB)
elif countAB == 0:
    count += min(countA, countB)

print(count)

Submission status: Accepted

Solution code:
N = int(input())
s=[input() for i in range(N)]
ans=0
for st in s:
    ans+= st.count("AB")

a_cnt=0
b_cnt=0
ab_cnt=0
for i in range(N):
    if s[i][-1]=="A":
        a_cnt+=1
    if s[i][0]=="B":
        b_cnt+=1
    if s[i][-1]=="A" and s[i][0]=="B":
        ab_cnt+=1
ans+=min(a_cnt,b_cnt)
if ab_cnt==b_cnt==a_cnt:
    if ab_cnt!=0:
        ans-=1

print(ans)

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())
S = [input() for _ in range(n)]

count = 0
ba = 0
wa = 0
bw = 0
for s in S:
    count += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        ba += 1
    elif s[0] == 'B':
        bw += 1
    elif s[-1] == 'A':
        wa += 1

if ba:
    count += ba - 1
    ba = 1
if ba:
    if wa and bw:
        count += 2
        wa -= 1
        bw -= 1
        ba -= 1
    if ba:
        if wa < bw:
            wa += 1
        else:
            bw += 1
count += min(wa,bw)

print(count)

Submission status: Accepted

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

cnt = 0
cntBA = 0
cntA = 0
cntB = 0
for i in s:
    for j in range(len(i) - 1):
        if i[j:j + 2] == "AB":
            cnt += 1
    #print(i)
    if i[0] == "B" and i[-1] == "A":
        cntBA += 1
    elif i[0] == "B":
        cntB += 1
    elif i[-1] == "A":
        #print(123)
        cntA += 1

#print(cnt, cntA, cntB, cntBA)
ans = cnt + max(0, cntBA - 1)
if cntBA > 0:
    ans += min(cntA, 1)
    cntA -= 1
    ans += min(cntB, 1)
    cntB -= 1
ans += max(min(cntA, cntB), 0)


print(ans)

Submission status: Accepted

Solution code:
N = int(input())

ab = 0 #naka
a = 0 #matsubinomi
b = 0 #sentounomi
ba = 0 #ryouhou

def count(s):
    l = len(s)
    ret = 0
    for i in range(l-1):
        if s[i] == 'A' and s[i+1] == 'B':
            ret += 1
    return ret

for _ in range(N):
    s = input()
    if s[-1] == 'A' and s[0] == 'B':
        ba += 1
    if s[-1] == 'A' and s[0] != 'B':
        a += 1
    if s[-1] != 'A' and s[0] == 'B':
        b += 1
    ab += count(s)
    
ans = ab
if ba > 0:
    ans += ba - 1
    if a > 0:
        a -= 1
        ans += 1
    if b > 0:
        b -= 1
        ans += 1
    ans += min(a,b)
else:
    ans += min(a,b)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = [''] * N
A = []
B = []
AB = []
cnt = 0
for i in range(N):
  S[i] = input()
  cnt += S[i].count('AB')
  if S[i][0] == 'B' and S[i][-1] == 'A':
    AB.append(i)
  elif S[i][-1] == 'A':
    A.append(i)
  elif S[i][0] == 'B':
    B.append(i)
cnt += max(len(AB) - 1, 0)
cnt += min(len(A), len(B))
if (len(A) or len(B)) and len(AB):
  cnt += 1
print(cnt)

Submission status: Accepted

Solution code:
n = int(input())

countA = 0
countB = 0
countAB = 0
kaburi = 0
for i in range(n):
    s = input()

    findAB = 0
    while(findAB != -1):
        findAB = s.find("AB", findAB)
        if(findAB != -1):
            countAB += 1
            findAB += 1

    flag = False
    if(s[0]=="B"):
        countB += 1
        flag = True
    if(s[len(s)-1]=="A"):
        countA += 1
        if(flag):
            kaburi += 1

ans = min(countA, countB) + countAB
if(countA==countB and countA==kaburi):
    if(countA != 0):
        ans -= 1
print(ans)

Submission status: Accepted

Solution code:
import collections as c
ip = lambda : map(int, input().split())

#################
N = int(input())
count_ab = 0
unchi = 0
clis = [0,0,0] # [f,b,f and b]

for i in range(N):
    s = input()
    if s[0] == 'B' and s[-1] == 'A':
        clis[2] += 1
    elif s[0] == 'B':
        clis[0] += 1
    elif s[-1] == 'A':
        clis[1] += 1
    for i in range(len(s)-1):
        if s[i:i+2] == 'AB':
            count_ab+=1
if clis[0] == 0 and clis[1] == 0 and clis[2] > 0:
    unchi = -1

#print(count_ab,clis)
print(min(clis[0:2]) + clis[2] + count_ab + unchi)