Problem:


Score : 400 points

Problem Statement

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

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

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

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

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4



Sample input:
3
ABCA
XBAZ
BAD


Sample output:
2

Submission status: Accepted

Solution code:
N = int(input())
ans = 0
d = {'A':0,'B':0,'BA':0}
for i in range(N):
    s = input()
    ans += s.count('AB')
    if s[0]!='B' and s[-1]!='A':
        continue
    else:
        if s[0]+s[-1]=='BA':
            d['BA']+=1
        else:
            if s[0]=='B':
                d['B']+=1
            else:
                d['A']+=1
        
ans += min(d['A'],d['B'])
if d['A']==0 and d['B']==0:
    ans += max(0,d['BA']-1)
else:
    ans += d['BA']
print(ans)

Submission status: Accepted

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

    inner = 0
    for s in S:
        inner += s.count("AB")
    
    # B_ended = 0
    # A_begin = 0

    A_ended = 0
    B_begin = 0
    both = 0
    for s in S:
        if s[0] == "B" and s[-1] == "A":
            both += 1   

        elif s[0] == "B": B_begin += 1
        elif s[-1] == "A": A_ended += 1

    mmA = 0
    if both > 0:
        if A_ended > 0:
            mmA += 1
            A_ended-=1
        if B_begin > 0:
            mmA += 1
            B_begin -= 1

    mmA += min(A_ended, B_begin)    
    if both > 0:
        mmA += both-1

    # if A_ended != B_begin:
    #     # 片方余ってるとき
    #     mmA += both
    # elif both > 0:
    #     mmA += both - 1 
    
    print(inner + mmA )
    

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
# import numpy as np
from collections import defaultdict
from collections import deque

N = int(input())
ss = list()
for i in range(N):
    ss.append(input())

types = list()
indices_dict = defaultdict(deque)
for i, s in enumerate(ss):
    if s[-1] == 'A':
        if s[0] != 'B':
            type_ = 0
        else:
            type_ = 1

    elif s[0] == 'B':
        type_ = 2
    else:
        type_ = 3
    types.append(type_)
    indices_dict[type_].append(i)

# print(indices_dict)
indices = list()
type_prev = 3
while True:
    # print(indices)
    # does not end with 'A'
    if type_prev in {2, 3}:
        if len(indices_dict[0]) != 0:
            idx = indices_dict[0].pop()
            indices.append(idx)
            type_prev = 0
        elif len(indices_dict[1]) != 0:
            idx = indices_dict[1].pop()
            indices.append(idx)
            type_prev = 1
        elif len(indices_dict[3]) != 0:
            idx = indices_dict[3].pop()
            indices.append(idx)
            type_prev = 3
        elif len(indices_dict[2]) != 0:
            idx = indices_dict[2].pop()
            indices.append(idx)
            type_prev = 2
        else:
            break

    # end with 'A'
    else:
        if len(indices_dict[1]) != 0:
            idx = indices_dict[1].pop()
            indices.append(idx)
            type_prev = 1
        elif len(indices_dict[2]) != 0:
            idx = indices_dict[2].pop()
            indices.append(idx)
            type_prev = 2
        elif len(indices_dict[3]) != 0:
            idx = indices_dict[3].pop()
            indices.append(idx)
            type_prev = 3
        elif len(indices_dict[0]) != 0:
            idx = indices_dict[0].pop()
            indices.append(idx)
            type_prev = 0
        else:
            break

st = ''
for idx in indices:
    st += ss[idx]

ans = 0
for i in range(len(st) - 1):
    if st[i] == 'A':
        if st[i + 1] == 'B':
            ans += 1
print(ans)
# heads = list()
# tails = list()
# for i, s in enumerate(ss):
#     if s[0] == 'B':
#         tails.append(i)

#     if s[-1] == 'A':
#         heads.append(i)

# for tail in tails:

Submission status: Accepted

Solution code:
N = int(input())

s = []
Binfront = 0
Ainend = 0
bothAB = 0
ABs = 0
for i in range(N):
    inputstring = input()
    s.append(inputstring)
    ABs += inputstring.count("AB")
    
    if inputstring[0] == "B" and inputstring[len(inputstring)-1] == "A":
        bothAB += 1
    elif inputstring[0] == "B":
        Binfront += 1
    elif inputstring[len(inputstring)-1] == "A":
        Ainend += 1


if bothAB > 0:
    ABs += bothAB - 1
    if Ainend > 0:
        ABs += 1
        Ainend -= 1
    if Binfront > 0:
        ABs += 1
        Binfront -= 1
ABs += min(Ainend,Binfront)

print(ABs)

Submission status: Accepted

Solution code:
N = int(input())
S = []
for i in range(N):
    S.append(input())
cnt = 0
cntA = 0
cntB = 0
cntAB = 0
for s in S:
    cnt += s.count('AB')
for s in S:
    if s[0] == 'B':
        cntB += 1
    if s[-1] == 'A':
        cntA += 1
    if s[0]=='B' and s[-1] =='A':
        cntAB += 1
if cntA == cntB == cntAB != 0:
    print(cnt + cntAB - 1)
else:
    print(cnt + min(cntA, cntB))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)


def read_int():
    return int(input())


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


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


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


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, S):
    ans = 0
    pre_b = set()
    post_a = set()
    for i, s in enumerate(S):
        if s[0] == 'B':
            pre_b.add(i)
        if s[-1] == 'A':
            post_a.add(i)
        ans += s.count('AB')
    # error_print(ans)
    both = pre_b & post_a
    if both:
        ans += len(pre_b & post_a) - 1
    pre_b -= both
    post_a -= both
    # print(pre_b, post_a)
    pbl = len(pre_b)
    pal = len(post_a)
    if both:
        if pbl == 0 and pal == 0:
            pass
        elif pbl == 0:
            # print(min(max(pbl, 1), max(pal, 1),))
            ans += min(1, pal)
        elif pal == 0:
            ans += min(1, pbl)
        else:
            ans += min(pbl+1, pal+1)
    else:
        ans += min(pbl, pal)
    return ans


def slv2(N, S):
    ans = 0
    for i in permutations(range(N), N):
        ans = max(ans, ''.join([S[j] for j in i]).count('AB'))
    return ans


def main():
    N = read_int()
    S = [read_str() for _ in range(N)]
    print(slv(N, S))
    # print(slv2(N, S))

    # for _ in range(1000):
    #     N = 5
    #     S = [''.join(random.choices('ABC', k=5)) for _ in range(N)]
    #     if slv2(N, S) != slv(N, S):
    #         print(S)
    #         break


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
ans = 0
a = 0
b = 0
both = 0

for i in range(n):
    s = input()
    ans += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        both += 1
    elif s[0] == 'B':
        b += 1
    elif s[-1] == 'A':
        a += 1
if a <= 0 or b <= 0:
    if a <= 0 and b <= 0:
        if both-1 > 0:
            ans += both-1
    else:
        ans += both
else:
    b -= 1
    a -= 1
    ans += both+1 + min(a,b)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = []
count = 0
countA = 0
countB = 0
countAB = 0
for i in range(N):
	S_in = str(input())
	for j in range(len(S_in)-1):
		if S_in[j:j+2] == 'AB':
			count += 1
	if (S_in[0] == 'B') & (S_in[-1] == 'A'):
		countAB	+= 1
	elif S_in[0] == 'B':
		countB += 1
	elif S_in[-1] == 'A':
		countA += 1
	S.append(S_in)
if (countA == 0) & (countB == 0) & (countAB > 0):
	print(max(0, count + countAB - 1))
else:
	print(count + countAB + min(countA, countB))

Submission status: Accepted

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

cnt = 0

ba=0
bx=0
xa=0
#print("")
for s in a:
  for i in range(len(s)):
    if i < len(s)-1:
      if s[i]=='A' and s[i+1]=='B':
        cnt+=1
        #print(s)
  if s[0]=='B' and s[-1:]=='A':
    ba += 1
  elif s[0]=='B':
    bx += 1
  elif s[-1:]=='A':
    xa += 1

if ba > 1:
  cnt += ba-1
  ba = 1
babx = min(ba,bx)
#print("min(ba,bx)=({},{})".format(ba,bx))
xaba = min(xa,ba)
#print("min(xa,ba)=({},{})".format(xa,ba))
xaax = min(bx - babx,xa-xaba)
#print("min(bx-babx,xa-xaba)=({},{})".format(bx-babx,xa-xaba))

print(cnt+babx+xaba+xaax)

Submission status: Accepted

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

cnt = 0
cnt1 = 0
cnt2 = 0
cnt3 = 0
for x in s:
    cnt += x.count("AB")
    if x[0] == "B":
        cnt1 += 1
    if x[-1] == "A":
        cnt2 += 1
    if x[0] == "B" and x[-1] == "A":
        cnt3 += 1

cnt1 -= cnt3
cnt2 -= cnt3

if cnt1+cnt2 > 0 or cnt3 == 0:
    print(cnt + cnt3 + min(cnt1, cnt2))
else:
    print(cnt + cnt3 + min(cnt1, cnt2) - 1)

Submission status: Accepted

Solution code:
n=int(input())
ss=[]
for _ in range(n):
    s=input()
    if 'A' in s or 'B' in s:
        ss.append(s)
c = sum(s.count('AB') for s in ss)
a = min(sum(s[0] == 'B' for s in ss), sum(s[-1] == 'A' for s in ss))
if a:
    c += a
    if sum((s[0] == 'B' and s[-1] != 'A') or (s[0] != 'B' and s[-1] == 'A') for s in ss) == 0:
        c -= 1
print(c)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
#[R,G,B,N] = list(map(int,input().split()))
N = int(input())
#N = 3
num_ab = 0
last_a = 0
top_b = 0
double_ab = 0
#s = ["ABCA",
#"XBAZ",
#"BAD"]
s = []
for i in range(N):
    s.append(str(input()))
for i in range(N):
    num_ab += s[i].count("AB")
    if s[i][0] == "B":
        if s[i][-1] == "A":
            double_ab += 1
        else:
            top_b += 1
    if s[i][-1] == "A":
        if s[i][0] != "B":
            last_a += 1

ans = 0
ans += num_ab
if double_ab > 0:
    ans += double_ab - 1
    if last_a > 0:
        ans += 1
        last_a -= 1
    if top_b > 0:
        ans += 1
        top_b -= 1
    ans += min(last_a,top_b)
else:
    ans += min(last_a,top_b)
print(ans)

Submission status: Accepted

Solution code:
n = input()
N = int(n)

count = 0
Acount = 0
AScount = 0
Bcount = 0
BScount = 0
BAcount = 0

for i in range(N):
    s = input()
    if 1 < len(s):
        if 'AB' in s:
            count += 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
    else:
        if s == 'B':
            BScount += 1
        if s == 'A':
            AScount += 1

BAcount += min(BScount, AScount)

if BScount <= AScount:
    Acount += AScount - BScount
else:
    Bcount += BScount - AScount

if 0 < BAcount:
    count += BAcount - 1
    BAcount = 1

if 0 < Acount and 0 < BAcount:
    count += 1
    Acount -= 1

if 0 < Bcount and 0 < BAcount:
    count += 1
    Bcount -= 1

count += min(Bcount, Acount)
print(count)

Submission status: Accepted

Solution code:
from sys import stdin
import math
import fractions
from collections import deque

INF = 10 ** 10

N = int(stdin.readline().rstrip())
s = [stdin.readline().rstrip() for _ in range(N)]

endA_num = 0
startB_num = 0
endA_startB_num = 0

cnt = 0
for si in s:
    if si[-1] == "A":
        endA_num += 1
        if si[0] == "B":
            endA_startB_num += 1
    if si[0] == "B":
        startB_num += 1

    for i in range(len(si)-1):
        if si[i] == "A" and si[i+1] == "B":
            cnt+=1

alpha = 0
if endA_num > 0 and startB_num > 0:
    if endA_num == startB_num and endA_num == endA_startB_num:
        endA_num -= 1
    alpha = min(endA_num, startB_num)

print(cnt+alpha)

Submission status: Accepted

Solution code:

N = int(input())

count = 0
count_a = 0
count_b = 0
count_all = 0
for i in range(N):
    s = input()
    for j in range(1,len(s)):
        if s[j] == 'B' and s[j-1] == 'A':
            count += 1
    if s[0] == 'B' and s[-1] == 'A':
        count_all += 1
        continue
    if s[0] == 'B':
        count_b += 1
    if s[-1] == 'A':
        count_a += 1

mx = max(count_a, count_b)
mn = min(count_a, count_b)
ans = count + mn
if count_all != 0:
    if count_a != 0 and count_b != 0:
        ans = count + (count_all-1+2) + (mn-1)
    if count_a == 0 and count_b == 0:
        ans = count + count_all - 1
    if count_a == 0 and count_b != 0:
        ans = count + count_all - 1 + 1
    if count_a != 0 and count_b == 0:
        ans = count + count_all -1 + 1

print(ans)

Submission status: Accepted

Solution code:
n = int(input())


cnt_ba = 0
cnt_a = 0
cnt_b = 0
ans = 0
for i in range(n):
      s = input()
      ans += s.count("AB")
      if s[0] == "B" and s[-1] == "A":
            cnt_ba += 1
      elif s[0] == "B":
            cnt_b += 1
      elif s[-1] == "A":
            cnt_a += 1
if n != 1:
      if cnt_ba != 0:
            tmp = cnt_ba-1
            if  cnt_a >= 1:
                  tmp += 1
                  cnt_a -= 1
            if  cnt_b >= 1:
                  tmp += 1
                  cnt_b -= 1
      else: tmp = 0
      print(ans + tmp + min(cnt_a, cnt_b))
else:
      print(ans)

Submission status: Accepted

Solution code:
N = int(input())
s = []
temp_sum = 0
A_or_B_count = [0,0]
AB_count = 0
for i in range(N):
	aaa = input()
	temp_sum += aaa.count("AB")
	if aaa[0] == "B" and aaa[-1] == "A":
		AB_count += 1
	elif aaa[-1] == "A":
		A_or_B_count[0] += 1
	elif aaa[0] == "B":
		A_or_B_count[1] += 1
A_or_B_count.sort()
if A_or_B_count[0] + AB_count > A_or_B_count[1]:
	if A_or_B_count[1] == 0:
		print(temp_sum + min(N-1,AB_count - 1))
	else:
		AB_count -= (A_or_B_count[1] - A_or_B_count[0])
		print(temp_sum + min(N-1,AB_count + A_or_B_count[1]))
else:
	print(temp_sum + min(N - 1,A_or_B_count[0] + AB_count))

Submission status: Accepted

Solution code:
N = int(input())
ans = 0
numb = 0
numa = 0
numba = 0
for _ in range(N):
    s = input()
    ans += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        numba += 1
    elif s[0] == "B":
        numb += 1
    elif s[-1] == "A":
        numa += 1

if numa == 0:
    if numb == 0:
        ans += max(0, numba - 1)
    else:
        ans += numba
else:
    if numba == 0:
        ans += min(numa, numb)
    elif numb == 0:
        ans += numba
    else:
        numa -= 1
        ans += numba + 1
        numb -= 1
        ans += min(numa, numb)
print(ans)

Submission status: Accepted

Solution code:
n =  int(input())
a,b,c,d = 0,0,0,0
for _ in [0]*n:
  s = input()
  if s[0] == "B" and  s[-1] == "A":
    d += 1
  elif s[0] == "B":
    b += 1
  elif s[-1] == "A":
    a += 1
  for i in range(len(s)-1):
    if s[i:i+2] == "AB":
      c += 1
if a == 0 and b == 0:
  c += max(d-1,0)
else:
   c += d + min(a,b)
print(c)

Submission status: Accepted

Solution code:
def countAB(S):
  ct=0
  flg = True
  pos=0
  while flg:
    idx = S.find('AB',pos)
    if idx!=-1:
      ct+=1
    else:
      flg = False
    pos = idx + 2
  return ct
 
N = int(input())
 
num_AB = 0
num_A = 0
num_B = 0
num_BA = 0
for n in range(N):
  S = input()
  num_AB += countAB(S)
  if S[len(S)-1]=='A':
    num_A += 1
  if S[0]=='B':
    num_B += 1
  if S[len(S)-1]=='A' and S[0]=='B': 
    num_BA += 1
    
num_AB_cmb = min(num_A,num_B)
if num_A == num_BA and num_B == num_BA and num_BA!=0:
  num_AB_cmb = num_BA-1
 
print("{0}".format(num_AB + num_AB_cmb))

Submission status: Accepted

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

ans = 0
A = B = BA = 0
for s in S:
    for i in range(len(s) - 1):
        if s[i] + s[i + 1] == 'AB':
            ans += 1

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


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

elif (A > 0) & (B > 0):
    ans += min(A, B)

elif A > 0:
    ans += BA

elif B > 0:
    ans += BA

elif BA > 0:
    ans += (BA - 1)

print(ans)

Submission status: Accepted

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

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

if a>b :
    print(ab+b)
elif a!=0 and a==b and bxxa==a:
    print(ab+a-1)
else: 
    print(ab+a)

Submission status: Accepted

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

a = 0
both = 0
b = 0
ans = 0
for i, s in enumerate(s_list):
    ans += s.count("AB")
    if s[0] == "B" and s[-1] == "A":
        both += 1

    elif s[-1] == "A":
        a += 1

    elif s[0] == "B":
        b += 1

if a != 0:
    a -= 1
    ans += both
    if b != 0:
        b -= 1
        ans += 1
    ans += min(a, b)
else:
    if b != 0:
        b -= 1
        ans += both
    else:
        if both >= 2:
            ans += both - 1
print(ans)

Submission status: Accepted

Solution code:
# coding: UTF-8
import sys
#sys.setrecursionlimit(n)
import heapq
import re
import bisect
import random
import math
import itertools
from collections import defaultdict, deque
from copy import deepcopy
from decimal import *

n = int(input())
AA = []
BA = []
BZ = []

AZ = []

count = 0
l = 0
AAc = 0
BAc = 0
BZc = 0
for i in range(n):
    t = input()
    count += t.count('AB')
    ss = list(t)
    if ss[0] == 'B' and ss[-1] == 'A':
        BA.append(1)
        BAc += 1
        l += 1
    elif ss[0] != 'B' and ss[-1] == 'A':
        AA.append(1)
        AAc += 1
        l += 1
    elif ss[0] == 'B' and ss[-1] != 'A':
        BZ.append(1)
        BZc += 1
        l += 1
if AAc != 0 and BAc != 0:
    count += BAc
    AAc -= 1
    if BZc != 0:
        BZc -= 1
        count += 1
    if AAc != 0 and BZc !=0:
        count += min(AAc,BZc)
elif AAc == 0 and BAc != 0:
    if BAc >= 2:
        count += BAc - 1
    if BZc > 0:
        count += 1
elif AAc != 0 and BAc ==0:
    count += min(AAc, BZc)
print(count)

Submission status: Accepted

Solution code:
n = int(input())
c = 0
xa = 0
bx = 0
ba = 0
for _ in range(n):
  si = str(input())
  l = len(si)
  s1 = si[0]
  s2 = si[-1]
  if s1=="B":
    if s2=="A":
      ba += 1
    else:
      bx += 1
  elif s2 == "A":
    xa += 1
  for i in range(l-1):
    if si[i]=="A" and si[i+1]=="B":
      c += 1
if ba == 0:
  print(c+min(bx,xa))
  exit()
if bx == 0:
  if  xa == 0:
    print(ba-1+c)
    exit()
  else:
    print(ba+c)
    exit()
if xa == 0:
  print(ba+c)
  exit()
print(min(bx,xa)+ba+c)

Submission status: Accepted

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

start = 0
end = 0
same = 0
c = 0
for x in s:
    c = c + len(x.split('AB')) - 1
    if x.startswith('B'):
        start += 1
        if x.endswith('A'):
            same += 1
    if x.endswith('A'):
        end += 1

if start == end:
    c += start
    if same > 0 and same == start:
        c  -= 1
elif start > end:
    c += end
else:
    c += start
print(c)

Submission status: Accepted

Solution code:
N = int(input())
c = 0
tail_A = 0
head_B = 0
B_A = 0
def count(S):
    if len(S) == 1:
        return 0
    c = 0
    for i in range(len(S)-1):
        if S[i] == 'A' and S[i+1] == 'B':
            c += 1
    return c

for _ in range(N):
    s = input()
    c += count(s)
    if s[-1] == 'A':
        if s[0] == 'B':
            B_A += 1
        else:
            tail_A += 1
    else:
        if s[0] == 'B':
            head_B += 1

if tail_A > 0 and head_B > 0:
    c = c + B_A + 1
    tail_A -= 1
    head_B -= 1
elif tail_A == 0 and head_B > 0:
    c = c + B_A
    head_B -= 1
elif tail_A > 0 and head_B == 0:
    c = c + B_A
    tail_A -= 1
else:
    if B_A >= 2:
        c = c + B_A - 1

c += min(tail_A, head_B)
print(c)

Submission status: Accepted

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

cnt = 0
enda = 0
startb = 0
ba = 0
for s in strs:
    cnt += s.count("AB")
    enda += 1 if (s[-1] == "A") else 0
    startb += 1 if (s[0] == "B") else 0
    ba += 1 if (s[0] == "B" and s[-1] == "A") else 0

cnt -= 1 if (ba != 0 and enda == ba and startb == ba) else 0

print(cnt + min(enda, startb))

Submission status: Accepted

Solution code:
N = int(input())

BA = 0
start_B = 0
end_A = 0

ans = 0
for _ in range(N):
    s = list(input())
    if s[0] == 'B' and s[-1] == 'A':
        BA += 1
    elif s[0] == 'B':
        start_B += 1
    elif s[-1] == 'A':
        end_A += 1
    for i in range(len(s)-1):
        if s[i] == 'A' and s[i+1] == 'B':
            ans += 1
ans += min(start_B, end_A)
if BA > 0:
    ans += BA - 1
if (start_B > 0 or end_A > 0) and BA > 0:
    ans += 1
print(ans)

Submission status: Accepted

Solution code:

N = int(input())
countA = 0
countB = 0
countC = 0
kcount = 0

for i in range(N):
    K = input()
    kcount += K.count("AB")
    K = list(K)
    if K[0] == "B" and K[-1] == "A":
        countC += 1 
    if K[-1] == "A":
        countA += 1
    if K[0] == "B":
        countB += 1
if countC>=1 and (countB-countC)==0 and (countA-countC)==0:
    print(kcount+countC-1)
elif countC >=1 and (countB-countC)==0 and (countA-countC)>=1:
    print(kcount+countC)
elif countC >=1 and (countB-countC)>=1 and (countA-countC)==0:
    print(kcount+countC)
elif countB > countA:
    print(kcount+countA)
else:
    print(kcount+countB)

Submission status: Accepted

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

c = 0
ca = 0
cb = 0
cab = 0

for s in sl:
  c += s.count('AB')
  if s[-1] == 'A':
    ca += 1
  if s[0] == 'B':
    cb += 1
  if s[-1] == 'A' and s[0] == 'B':
    cab += 1

t = min(ca, cb)
if ca == cb and cb == cab and ca > 0:
  t -= 1
print(c + t)

Submission status: Accepted

Solution code:
def solve():
    N = int(raw_input())
    S = []
    for i in range(N):
        S.append(raw_input())
    has_AB = 0
    end_byA = 0
    start_byB = 0
    B_A = 0
    for i in range(N):
        if S[i][0] == 'B':
            if S[i][-1] == 'A':
                B_A += 1
            else:
                start_byB += 1
        if S[i][-1] == 'A':
            if S[i][0] != 'B':
                end_byA += 1
        for j in range(len(S[i]) - 1):
            if S[i][j:(j+2)] == 'AB':
                has_AB += 1
    if end_byA == 0 and start_byB == 0:
        ret = has_AB + max(B_A - 1, 0)
    else:
        ret = has_AB + min(end_byA + B_A, start_byB + B_A)
    print str(ret)

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
N = int(input())
s = []
ab_num = 0
b_start = 0
a_end = 0
ba_word = 0
for i in range(N):
    tmp = input()
    s.append(tmp)
    rep = tmp.replace("AB", "")
    ab_num += (len(tmp) - len(rep)) // 2
    if tmp[0] == "B":
        b_start += 1
    if tmp[-1] == "A":
        a_end += 1
    if tmp[0] == "B" and tmp[-1] == "A":
        ba_word += 1
if b_start == a_end == ba_word != 0:
    print(max(ab_num + min(a_end, b_start) - 1, 0))
else:
    print(ab_num + min(a_end, b_start))

Submission status: Accepted

Solution code:
N = int(input())
c = 0
A = 0
B = 0
BA = 0
for i in range(N):
  tmp = input()
  if (tmp[0] == 'B') & (tmp[-1] == 'A'):
    BA += 1
  elif (tmp[0] == 'B'):
    B += 1
  elif (tmp[-1] == 'A'):
    A += 1 
  c += tmp.count('AB')
if BA >= 1:
  c += BA-1
  if B >= 1:
    B -=1
    c += 1
  if A >= 1:
    A -= 1
    c += 1
c += min(A,B)
print(c)

Submission status: Accepted

Solution code:
import re

N=int(input())
s =[]
for i in range(N):
    s.append(str(input()))

counter = 0
B_begin=0
A_end =0
AB_in =0
B_begin_and_A_end = 0


for i in range(N):
    m = len(re.findall('AB',s[i]))
    AB_in += m

    chech_b = False
    chech_a = False

    if s[i][0]=='B':
        B_begin +=1
        chech_b = True

    if s[i][-1]=='A':
        A_end+=1
        chech_a = True

    if chech_a and chech_b:
        B_begin_and_A_end+=1

ans = 0 
mini = min(B_begin, A_end)

if mini ==0:
    ans = AB_in

elif B_begin == A_end == B_begin_and_A_end:
    if mini!=0:
        ans = AB_in + mini -1

else:
    ans = AB_in + mini

print(ans)

Submission status: Accepted

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

base = sum(x.count('AB') for x in s)

same_pattern = a_n = b_n = 0
for x in s:
    b = x[0]
    a = x[len(x)-1]
    if b == 'B':
        b_n += 1
    if a == 'A':
        a_n += 1
    if a == 'A' and b == 'B':
        same_pattern += 1

if same_pattern > 0 and same_pattern == max(a_n, b_n):
    print(base + max(a_n, b_n) - 1)
else:
    print(base + min(a_n, b_n))

Submission status: Accepted

Solution code:
import sys
rr = lambda: sys.stdin.readline().strip()
ri = lambda: int(rr())
rs = lambda: [int(_) for _ in rr().split()]

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

a = 0
b = 0
c = 0
cnt = 0
for s in S:
    f = False
    for si in s:
        if not f:
            if si == 'A':
                f = True
        else:
            if si != 'A':
                f = False
            if si == 'B':
                cnt += 1
    if s[-1] == 'A':
        if s[0] == 'B':
            c += 1
        else:
            a += 1
    elif s[0] == 'B':
        b += 1

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

print(cnt)

Submission status: Accepted

Solution code:
n = int(input())

count = 0
b = 0
a = 0
ba = 0

for _ in range(n):
  s = input()
  count += s.count("AB")
  if s[0] is "B":
    if s[-1] is "A":
      ba += 1
    else:
      b += 1
  elif s[-1] is "A":
      a += 1

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

Submission status: Accepted

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


ba = 0
a = 0
b = 0
ans = 0
#ただsをつなげていく(元々入ってたABを数えるため)
simples = ''
#前の最後がaだったか
a_flag = False
#最後に引く
bias = 0
for i in range(N):
    simples += s[i]
    if s[i][-1]=="A" and s[i][0]=="B":
        if a_flag:
            bias += 1
        a_flag = True
        ba += 1
    elif s[i][-1]=="A":
        a_flag = True
        a += 1
    elif s[i][0]=="B":
        if a_flag:
            bias += 1
            a_flag = False
        b += 1
    else:
        a_flag = False
        continue

ans += simples.count("AB") - bias
if a>0 or b > 0:
    ans += ba
    ans += min(a,b)

if a==0 and b == 0:
    if ba > 1:
        ans += ba-1

print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 5)

N = int(input())
right_A = 0
left_B = 0
B_to_A = 0
AB_count = 0

for _ in range(N):
    target = input()
    AB_count += target.count('AB')
    if target[0] == 'B' and target[-1] == 'A':
        B_to_A += 1
    elif target[0] == 'B':
        left_B += 1
    elif target[-1] == 'A':
        right_A += 1

def recursive(x, y, z):
    if z == 0:
        return min(x, y)
    elif x == y == 0:
        return z - 1
    else:
        return recursive(x, y, z-1) + 1

print(recursive(right_A, left_B, B_to_A) + AB_count)

Submission status: Accepted

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

def countAB(str):
    count = 0
    for i in range(len(str)-1):
        if (str[i] == 'A') & (str[i+1] == 'B'):
            count += 1
    return(count)

def countRest(x, y, z):
    if(x > 0) | (y > 0):
        count = z + min(x, y)
    else:
        if(z > 1):
            count = z - 1
        else:
            count = 0
    return(count)

count = 0
count_bxa = 0
count_xa = 0
count_bx = 0
for s in s_list:
    count += countAB(s)
    if ((s[-1] == 'A') & (s[0] == 'B')):
        count_bxa += 1
    elif (s[-1] == 'A'):
        count_xa += 1
    elif (s[0] == 'B'):
        count_bx += 1

print(count + countRest(count_xa, count_bx, count_bxa))

Submission status: Accepted

Solution code:
N = int(input())
left, right, both = 0, 0, 0
ans = 0
for i in range(N):
    s = input()
    if s[0] == "B":
        if s[-1] == "A":
            both += 1
        else:
            left += 1
    elif s[-1] == "A":
        right += 1
    for j in range(len(s) - 1):
        if s[j] == "A" and s[j + 1] == "B":
            ans += 1
# print(left, right, both, ans)

if min(left, right) >= 1:
    bonus = min(left, right) + both

elif max(left, right) == 0:
    bonus = max(both - 1, 0)

else:
    bonus = both

print(ans + bonus)

Submission status: Accepted

Solution code:
n = int(input())
lis = [input() for _ in range(n)]
cnt = sum([l.count('AB') for l in lis])
ab_cnt = sum([l[-1] == 'A' and l[0] == 'B' for l in lis])
a_cnt = sum([l[-1] == 'A' for l in lis]) - ab_cnt
b_cnt = sum([l[0] == 'B' for l in lis]) - ab_cnt
if ab_cnt:
  cnt += ab_cnt - 1
  if a_cnt or b_cnt:
    a_cnt += 1
    b_cnt += 1
print(cnt + min(a_cnt, b_cnt))

Submission status: Accepted

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

def solve():
    NAB, NBA, NB_, N_A = 0, 0, 0, 0
    for _ in range(int(input())):
        S = input()
        NAB += S.replace('AB', '-').count('-')
        b, a = S.startswith('B'), S.endswith('A')
        NBA += (b and a)
        NB_ += (b and (not a))
        N_A += ((not b) and a)
    res = NAB + max(NBA-1, 0) + (NB_>=1 and NBA>=1) + (N_A>=1 and NBA>=1) + max(min(NB_, N_A)-(NBA>=1), 0)

    return str(res)

if __name__ == '__main__':
    print(solve())

Submission status: Accepted

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

XA = 0
BX = 0
BXA = 0
cnt = 0
for Si in S:
    cnt += Si.count("AB")

    tp = (Si[0] == "B")*1 + (Si[-1] == "A")*2
    if tp == 1:
        BX += 1
    elif tp == 2:
        XA += 1
    elif tp == 3:
        BXA += 1

if BXA > 0:
    cnt += BXA - 1
    BXA = 1

if BXA > 0:
    if BX > 0:
        cnt += 1
        BX -= 1
    if XA > 0:
        cnt += 1
        XA -= 1

pair = min(BX, XA)
if pair > 0:
    cnt += pair
    BX -= pair
    XA -= pair


print(cnt)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
a = int(input())
s = 0
A=B=AB=0

d = {"A":0,"B":0}
for i in range(a):
    t = input()
    s+=t.count("AB")
    if t[0]=="B" and t[-1]=="A":AB+=1
    elif t[0]=="B":B+=1
    elif t[-1]=="A":A+=1
res = 0
if A==0 and B == 0 and AB >0:
    res = AB-1
elif A==0 and B == 0:
    res = 0 
elif A==1 and B == 0:
    res = AB
elif A==0 and B ==1:
    res = AB
else:
    res = AB+1 + min(A-1,B-1)
print(res+s)