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:
# -*- coding:utf-8 -*-
"""
.....A
B.....
を連結させればABは一個増える

(例)
...A
B...
B..A
が一個ずつある時、

...A B..A B...
とやる2が正解で、

...A B... B..A
とやると1で不正解

"""
def solve():
    N = int(input())

    ans = 0
    b_start = 0
    a_end = 0
    ryouhou = 0
    for i in range(N):
        s = input()
        ans += s.count("AB")
        
        if s[0] == "B" and s[-1] == "A":
            ryouhou += 1
        elif s[0] == "B":
            b_start += 1
        elif s[-1] == "A":
            a_end += 1
    
    # まず、ryouhouを可能な限りつなげる
    if ryouhou > 0:
        ans += ryouhou - 1

        # 両端にb_startとa_endをくっつけれるならそうする
        if b_start > 0:
            b_start -= 1
            ans += 1
        if a_end > 0:
            a_end -= 1
            ans += 1
    
    # 残ったb_startとa_endでABを作る
    ans += min(b_start, a_end)

    print(ans)
   
        

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
n = int(input())
XA ,BA ,BX = 0 ,0 ,0
AB = 0
for i in range(n):
    s = str(input())
    AB += s.count("AB")
    if s[0] == "B":
        if s[-1] == "A":
            BA += 1
        else:
            BX += 1
    else:
        if s[-1] == "A":
            XA += 1

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

Submission status: Accepted

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

if AB:
    ans += AB-1
    if A:
        ans += 1
        A -= 1
    if B:
        ans += 1
        B -= 1

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

Submission status: Accepted

Solution code:
N=int(input())
A=0
B=0
ans=0
AB=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
C=min(A,B)
if A==0 and B==0:
    print(ans+max(0,AB-1))
elif C==0:
    print(ans+AB)
else:
    print(ans+AB+min(A,B))

Submission status: Accepted

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

count = 0
count_a = 0
count_b = 0
count_ab = 0
for i in range(n):
    if s[i][0] =='B' and s[i][-1] =='A':
        count_ab = count_ab + 1
    elif s[i][0] =='B':
        count_b = count_b + 1
    elif s[i][-1] =='A':
        count_a = count_a + 1
    
    count = count + s[i].count('AB')

if count_ab!=0 and count_b==0 and count_a ==0:
    count = count + count_ab-1
elif count_b==0 and count_a ==0:
    count = count
else:
    count = count +min(count_a,count_b) + count_ab

print(count)

Submission status: Accepted

Solution code:
N = int(input())
count = 0
end = 0
start = 0
double = 0
for i in range(N):
    line = input()
    if "AB" in line:
        count += line.count("AB")
    if line[0] == "B":
        if line[-1] == "A":
            double +=1
        else:
            start += 1
    elif line[-1] == "A":
            end += 1
if double == 0:
    count += min(start, end)
elif start + end > 0:
    count += double + min(start, end)
elif start + end == 0:
    count += double - 1
print(count)

Submission status: Accepted

Solution code:
import math
import fractions
import copy
import numpy as np
#以下てんぷら
def j(q):
    if q==1: print("POSSIBLE")
    elif q == 0:print("IMPOSSIBLE")
    exit(0)
rem = pow(10,9)+7
"""
def ct(x,y):
    if (x>y):print("+")
    elif (x<y): print("-")
    else: print("?")
"""

def ip():
    return int(input())
def printrow(a):
    for i in a:
        print(i)
def combinations(n,r):
    if n<r:return 0
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
def permutations(n,r):
    if n<r:return 0
    return math.factorial(n) // math.factorial(n - r)
def lcm(x, y):
    return (x * y) // fractions.gcd(x, y)


n = ip()                                     #入力整数1つ
#n,m= (int(i) for i in input().split())       #入力整数横2つ以上
#a = [int(i) for i in input().split()]        #入力整数配列
#a = input()                                  #入力文字列
#a = input().split()                          #入力文字配列
#n = ip()                      #入力セット(整数改行あり)(1/2)
#a=[ip() for i in range(m)]    #入力セット(整数改行あり)(2/2)
a=[input() for i in range(n)]    #入力セット(整数改行あり)(2/2)
#jの変数はしようできないので注意
#全足しにsum変数使用はsum関数使用できないので注意
#a.pop(0)は10^5あるときTLEしやすい!注意!抜くなら逆ソート!
#これを消すとなぜかWAになる呪い
type = [0 for i in range(4)]
s = 0
for i in a:
    s+=i.count("AB")
    if i[0] == 'B' and i[-1] == 'A': type[0]+=1    # B***A
    elif i[0] == 'B' and i[-1] != 'A': type[1]+=1  # B****
    elif i[0] != 'B' and i[-1] == 'A': type[2]+=1  # ****A
    elif i[0] != 'B' and i[-1] != 'A': type[3]+=1  # *****
if type[0] == 0:
    s+=min(type[1],type[2])
else:
    if type[1] or type[2]:
        s+=type[0]+ min(type[1],type[2])
    else:
        s+=type[0]-1
print(s)

Submission status: Accepted

Solution code:
# wrong answer...
# 正解はこちら　https://img.atcoder.jp/diverta2019/editorial.pdf

import math
N = int(input())
l = []
for i in range(N):
   l.append(input())

default = sum([i.count('AB') for i in l])

#only末尾Aの数
a = sum([i[-1]=='A' and i[0]!='B' for i in l])
#only先頭Bの数
b = sum([i[0]=='B' and i[-1]!='A' for i in l])
#先頭Bかつ末尾Aの数
ab = sum([i[0]=='B' and i[-1]=='A' for i in l])

num = 0
if ab == 0:
    num = min(a, b)
elif a + b > 0: # a, bの少なくとも一方は0出ない場合
    num = min(a, b) + ab
else:
    num = ab -1

print(num + default)

Submission status: Accepted

Solution code:
N = int(input())

innerAB_cnt = 0
endA_cnt = 0
startB_cnt = 0
B_A_cnt = 0
for i in range(N):
    S = input()
    innerAB_cnt += S.count('AB')
    is_end_A = S[-1] == 'A'
    is_start_B = S[0] == 'B'
    if is_end_A and is_start_B:
        B_A_cnt += 1
    elif is_end_A:
        endA_cnt += 1
    elif is_start_B:
        startB_cnt += 1
remainder = abs(startB_cnt - endA_cnt)
if B_A_cnt == 0:
    print(min(endA_cnt, startB_cnt) + innerAB_cnt)
elif endA_cnt + startB_cnt > 0:
    print(min(endA_cnt, startB_cnt) + B_A_cnt + innerAB_cnt)
else:
    print(B_A_cnt-1 + innerAB_cnt)

Submission status: Accepted

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


def solve(N: int, S: "List[str]"):
    cnt = 0
    
    cnt_ba = 0
    cnt__a = 0
    cnt_b_ = 0

    for s in S:
        cnt += 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 cnt_ba > 0:
        cnt += cnt_ba - 1
        if cnt__a > 0:
            cnt += 1
            cnt__a -= 1

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

    cnt += min(cnt__a,cnt_b_)


    print(cnt)



    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
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:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LS()
    return l
sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():
    n,k = LI()
    print(n-k+1)
    return

#B
def B():
    r,g,b,n = LI()
    ans = 0
    for i in range(n+1):
        x = r*i
        for j in range(n+1-x):
            y = g*j
            z = n-x-y
            if z%b != 0 or z < 0:continue
            ans += 1
    print(ans)
    return

#C
def C():
    n = I()
    s = SR(n)
    f = [0 for i in range(n)]
    a = deque()
    b = deque()
    ba = deque()
    c = deque()
    l = 0
    for i in range(n):
        l += len(s[i])
        if s[i][-1] == "A":
            f[i] += 1
        if s[i][0] == "B":
            f[i] += 2
        if f[i] == 0:
            c.append(s[i])
        elif f[i] == 1:
            a.append(s[i])
        elif f[i] == 2:
            b.append(s[i])
        else:
            ba.append(s[i])
    ans = [None for i in range(l)]
    i = 0
    while a or b or c or ba:
        if a:
            x = a.popleft()
            for j in x:
                ans[i] = j
                i += 1
            while ba:
                x = ba.popleft()
                for j in x:
                    ans[i] = j
                    i += 1
            if b:
                x = b.popleft()
                for j in x:
                    ans[i] = j
                    i += 1
        elif b:
            x = b.popleft()
            for j in x:
                ans[i] = j
                i += 1
        elif c:
            x = c.popleft()
            for j in x:
                ans[i] = j
                i += 1
        while ba:
            x = ba.popleft()
            for j in x:
                ans[i] = j
                i += 1
    s = 0
    for i in range(l-1):
        if ans[i] == "A" and ans[i+1] == "B":
            s += 1
    print(s)
    return

#D
def D():
    n = I()

    return

#E
def E():
    n = I()

    return

#F
def F():
    n = I()

    return

#G
def G():
    n = I()

    return

#H
def H():
    n = I()

    return

#I
def I_():
    n = I()

    return

#J
def J():
    n = I()

    return

#Solve
if __name__ == "__main__":
    C()

Submission status: Accepted

Solution code:
import numpy as np

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


ABarray = np.zeros((N, 2), dtype=int)
count = 0
for i, alp in enumerate(s):
    ABarray[i, 0] = 1 if (alp[-1] == 'A') else 0
    ABarray[i, 1] = 1 if (alp[0] == 'B') else 0
    count += alp.count('AB')

both = np.count_nonzero(np.all(ABarray == 1, axis=1))
ABsum = np.sum(ABarray, axis=0)
Aonly = ABsum[0] - both
Bonly = ABsum[1] - both

if Aonly == 0 and Bonly == 0 and both >= 1:
    count += both - 1
else:
    count += min(Aonly, Bonly) + both
print(count)

Submission status: Accepted

Solution code:
import numpy as np

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


ABarray = np.zeros((N, 3), dtype=int)
count = 0
for i, alp in enumerate(s):
    ABarray[i, 0] = 1 if (alp[-1] == 'A') else 0
    ABarray[i, 1] = 1 if (alp[0] == 'B') else 0
    ABarray[i, 2] = 1 if (alp[0] == 'B' and alp[-1] == 'A') else 0
    count += alp.count('AB')

ABsum = np.sum(ABarray, axis=0)
both = ABsum[2]
Aonly = ABsum[0] - both
Bonly = ABsum[1] - both

if Aonly == 0 and Bonly == 0 and both >= 1:
    count += both - 1
else:
    count += min(Aonly, Bonly) + both
print(count)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())

c = 0
sb = ea = both = 0
for i in range(N):
    s = input()
    c += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        both += 1
    elif s[0] == 'B':
        sb += 1
    elif s[-1] == 'A':
        ea += 1

if both > 0:
    c += both-1
    if sb > 0:
        c += 1
        sb -= 1
    if ea > 0:
        c += 1
        ea -= 1
    c += min(sb, ea)
else:
    c += min(sb, ea)

print(c)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
N=int(input())
cnt=0
ba=0
a=0
b=0

for i in range(N):
    chr=input()
    cnt+=chr.count('AB')
    if chr[0]=='B' and chr[-1]=='A':
        ba+=1
    elif chr[-1]=='A':
        a+=1
    elif chr[0]=='B':
        b+=1

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

Submission status: Accepted

Solution code:
N = int(input())
cnt = 0
end_A = 0
start_B = 0
start_B_AND_end_B = 0
for _ in range(N):
    s = input()
    if s.startswith('B') and s.endswith('A'):
        start_B_AND_end_B += 1
    elif s.startswith('B'):
        start_B += 1
    elif s.endswith('A'):
        end_A += 1
    
    cnt += s.count('AB')
    
    
if start_B_AND_end_B >= 1:
    cnt += start_B_AND_end_B - 1
    if end_A >= 1:
        cnt += 1
        end_A -= 1
    if start_B >= 1:
        cnt += 1
        start_B -= 1

cnt += min(end_A, start_B)

print(cnt)

Submission status: Accepted

Solution code:
n=int(input())
counta=0
countb=0
countspec=0
re=0
for i in range(n):
    s=input()
    re+=s.count("AB")
    if (s[0]=='B') and s[len(s)-1]=='A':
        countspec+=1
    else:
        if s[0]=='B':
            countb+=1
        else:
            if (s[len(s)-1]=='A'):
                counta+=1
if countspec>=1:
    re+=countspec-1
if countspec>=1:
    if counta>=1:
        counta-=1
        re+=1
    if countb>=1:
        countb-=1
        re+=1
re+=min(counta,countb)
print(re)

Submission status: Accepted

Solution code:
N = int(input())
S = []
for i in range(N):
    s = str(input())
    S.append(s)
    
count_AB = 0
for s in S:
    count_AB += s.count("AB")
# print(count_AB)

count_BA = 0
count_A = 0
count_B = 0
for s in S:
    if s[0] == 'B' and s[-1] == 'A':
        count_BA += 1
    if s[0] != 'B' and s[-1] == 'A':
        count_A += 1
    if s[0] == 'B' and s[-1] != 'A':
        count_B += 1
# print(count_BA, count_A, count_B)

if count_BA >= 1:
    count_AB += count_BA -1
if count_BA >= 1:
    if count_A >= 1:
        count_A -= 1
        count_AB += 1
    if count_B >= 1:
        count_B -= 1
        count_AB += 1
count_AB += min(count_A, count_B)
print(count_AB)

Submission status: Accepted

Solution code:
n = int(input())
ss = [input() for _ in range(n)]
ans = 0
count_ab = 0 # if ab exists
count_a = 0 # if end in a
count_b = 0 # if start in b
count_ba = 0 # if start in b and end in a
for s in ss:
  slen = len(s)
  if s[0] == 'B' and  s[-1] == 'A':
    count_ba +=1
  else:
      if s[0] == 'B':
        count_b +=1
      if s[-1] == 'A':
        count_a +=1
  count_ab += s.count("AB")
 
if count_ba == 0:
    print(count_ab + min(count_a, count_b))
elif count_a == 0 and count_b == 0:
    print(count_ab + count_ba - 1)
elif count_a > 0 and count_b > 0:
    print(count_ab +  min(count_a, count_b) + count_ba)
else:
    print(count_ab + count_ba)

Submission status: Accepted

Solution code:
n = int(input())
a = 0
b = 0
ab = 0
total = 0
t = []

for i in range(n):
	t.append(input())

for i in t:
	total += i.count("AB")
	if i[-1] == "A" and i[0] == "B":
		ab += 1
	else:
		a += i[-1] == "A"
		b += i[0] == "B"
if ab == 0:
	print(total + min(a,b))
elif a == 0 and b == 0:
	print(total + ab - 1)
elif a > 0 and b > 0:
	print(total + ab + min(a, b))
else:
	print(total + ab)

Submission status: Accepted

Solution code:
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
from functools import lru_cache
import sys
sys.setrecursionlimit(10000)
INF = float("inf")
YES, Yes, yes, NO, No, no = "YES", "Yes", "yes", "NO", "No", "no"
dy4, dx4 = [0, 1, 0, -1], [1, 0, -1, 0]
dy8, dx8 = [0, -1, 0, 1, 1, -1, -1, 1], [1, 0, -1, 0, 1, 1, -1, -1]


def inside(y, x, H, W):
    return 0 <= y < H and 0 <= x < W


def ceil(a, b):
    return (a + b - 1) // b


# aとbの最大公約数
def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)

# aとbの最小公倍数
def lcm(a, b):
    g = gcd(a, b)
    return a / g * b


def main():
    N = int(input())

    ans = 0
    a, b, ba = 0, 0, 0
    for _ in range(N):
        S = input()
        ans += S.count("AB")

        if S[0] == "B" and S[-1] == "A":
            ba += 1
        elif S[-1] == "A":
            a += 1
        elif S[0] == "B":
            b += 1

    # A B A B
    if a > 0 and ba:
        a -= 1
        ans += ba

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

    # A B
    ans += min(a, b)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys,random
try: sys.stdin = open('in.in','r')
except: pass

ans = 0
allboth = 1
l = r = 0

n = int(input())
for i in range(n):
	s = input().strip()
	ans += s.count('AB')
	if s[0] == 'B' or s[-1] == 'A':
		l += s[0] == 'B'
		r += s[-1] == 'A'
		if s[0] != 'B' or s[-1] != 'A':
			allboth = 0

ans += min(l,r)
if allboth and l:
	ans -= 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s_list = [input() for x in range(n)]

cnt = 0
a_cnt = 0
b_cnt = 0
ab_cnt = 0
for x in s_list:
    cnt += x.count("AB")
    if (x[-1] == "A")&(x[0] != "B"):
        a_cnt += 1
    if (x[0] == "B")&(x[-1] != "A"):
        b_cnt += 1
    if (x[-1] == "A")&(x[0] == "B"):
        ab_cnt += 1
if ab_cnt == 0:
    print(cnt+min(a_cnt,b_cnt))
elif (a_cnt+b_cnt>0)&(ab_cnt != 0):
    print(cnt+ab_cnt+min(a_cnt,b_cnt))
elif (a_cnt+b_cnt==0):
    print(cnt+ab_cnt-1)

Submission status: Accepted

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

cnta = 0
cntb = 0
isok = False
cnt = 0


for i in range(n):
    if s[i][0] == 'B' and s[i][-1] =='A':
        cnta+=1
        cntb+=1
    elif s[i][0] =='B':
        cntb+=1
        isok = True
    elif s[i][-1] =='A':
        cnta+=1
        isok=True
    for j in range(len(s[i])-1):
        if s[i][j] =='A' and s[i][j+1] == 'B':
            cnt += 1


if isok:
    print(min(cnta,cntb)+cnt)
else:
    print(max(cnta-1,0)+cnt)

Submission status: Accepted

Solution code:
N=int(input())
st=[0]*N
for i in range(N):
    st[i]=input()
ans=0
c1=0 #b_start,a_end
c2=0#b_start
c3=0#a_end
for i in st:
    ans+=i.count("AB")
    if i[0]=="B" and i[-1]=="A":
        c1+=1
    elif i[0]=="B":
        c2+=1
    elif i[-1]=="A":
        c3+=1
if c1==0:
    ans+=min(c2,c3)
elif c2+c3>0:
    ans=ans+c1+min(c2,c3)
else:
    ans=ans+c1-1
print(ans)

Submission status: Accepted

Solution code:
#coding:utf-8
import itertools

N = int(input())
li = []
lasta = 0
firstb = 0
ab = 0
cnt = 0

# 各入力のABの数を求める
# HeadにBもしくはTailにAを持つリストをカウント
for i in range(N):
    s = input()
    cnt += s.count('AB')
    li = list(s)
    if li[-1] == 'A' and li[0] != 'B':
        lasta += 1
    if li[0] == 'B' and li[-1] != 'A':
        firstb += 1
    if li[-1] == 'A' and li[0] == 'B':
        ab += 1


# print('lasta : %d firstb : %d ab : %d cnt : %d' % (lasta, firstb, ab, cnt))
if ab == 0:
    cnt += min(lasta,firstb)
elif ab != 0 and lasta + firstb > 0:
    cnt += ab + min(lasta, firstb)
elif ab != 0 and lasta + firstb == 0:
    cnt += ab - 1

print(cnt)

Submission status: Accepted

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

ans = 0

leftB = rightA = leftB_and_rightA = 0

for l in L :
    ans += l.count("AB")
    if (l[0] != "B") and (l[-1] != "A") :
        continue
    elif (l[0] == "B") and (l[-1] != "A") :
        leftB += 1
    elif (l[0] != "B") and (l[-1] == "A") :
        rightA += 1
    else :
        leftB_and_rightA += 1

if leftB_and_rightA :
    ans += (leftB_and_rightA - 1)
    
    if leftB :
        ans += 1
        leftB -= 1
    
    if rightA :
        ans += 1
        rightA -= 1

ans += min(leftB, rightA)

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for i in range(N)]
cnt_ab_from_S = sum([s.count('AB') for s in S])
start_from_b_and_end_at_a = sum([(s[0] == 'B') and (s[-1] == 'A') for s in S])
not_start_from_b_and_end_at_a = sum([(s[0] != 'B') and (s[-1] == 'A') for s in S])
start_from_b_and_not_end_at_a = sum([(s[0] == 'B') and (s[-1] != 'A') for s in S])
ans = cnt_ab_from_S
if (start_from_b_and_end_at_a == 0):
    ans += min(not_start_from_b_and_end_at_a, start_from_b_and_not_end_at_a)
elif (not_start_from_b_and_end_at_a + start_from_b_and_not_end_at_a == 0):
    ans += (start_from_b_and_end_at_a - 1)
else:
    ans += (start_from_b_and_end_at_a + min(not_start_from_b_and_end_at_a, start_from_b_and_not_end_at_a))
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
C - AB Substrings
https://atcoder.jp/contests/diverta2019/tasks/diverta2019_c

"""
import sys


def solve(N, words):
    eA, sB, both = 0, 0, 0
    ans = 0
    for w in words:
        ans += w.count('AB')
        if w[-1] == 'A':
            if w[0] == 'B':
                both += 1
            else:
                eA += 1
        elif w[0] == 'B':
            sB += 1

    if both == 0:
        ans += min(eA, sB)
    elif eA == 0 and sB == 0:
        ans += (both - 1)
    else:
        ans += min(eA, sB) + both
    return ans


def main(args):
    N = int(input())
    words = [input() for _ in range(N)]
    ans = solve(N, words)
    print(ans)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Accepted

Solution code:
import re
N = int(input())
S = []
a, b, ab,c = 0, 0, 0, 0
for i in range(N):
	S.append(input())
	c += len(re.findall("AB", S[i]))
	if S[i][-1] == "A" and S[i][0] == "B":
		ab += 1
	if S[i][-1] == "A":
		a += 1
	if S[i][0] == "B":
		b += 1
if ab == a == b:
	seq = max(ab -1, 0)
else:
	seq = min (a,b)

print(seq + c)

Submission status: Accepted

Solution code:
N = int(input())
ans = 0
c1 = 0
c2 = 0
c3 = 0
ans = 0
for _ in range(N):
    s = input()
    ans += s.count("AB")
    if (s[0]=="B") & (s[-1]=="A"):
        c1 += 1
    elif s[0] == "B":
        c2 += 1
    elif s[-1]=="A":
        c3 += 1

if c1== 0:
    print(ans + min(c2, c3))
elif (c1 > 0) & (max(c2, c3) == 0):
    print(ans + c1 - 1)
elif (c1 > 0) & (max(c2, c3) > 0):
    print(ans + c1 + min(c2, c3))

Submission status: Accepted

Solution code:
n = int(input())

counter = 0

b_and_a = 0
first_b = 0
last_a = 0
for _ in range(n):
    w = input()
    counter += w.count("AB")

    if w[0] == "B" and w[-1] == "A":
        b_and_a += 1
    elif w[0] == "B":
        first_b += 1
    elif w[-1] == "A":
        last_a += 1
    else:
        pass

if b_and_a == 0:
    counter += min(first_b, last_a)
else:
    if b_and_a >= 2:
        counter += (b_and_a - 1)

    if first_b >= 1:
        counter += 1
        first_b -= 1
    if last_a >= 1:
        counter += 1
        last_a -= 1

    counter += min(first_b, last_a)

print(counter)

Submission status: Accepted

Solution code:
N = int(input())

countXA = 0
countBX = 0
countBXA = 0
countAB = 0

for i in range(N):
  line = input()
  if line[0] == 'B' and line[-1] == 'A':
    countBXA += 1
  elif line[0] == 'B':
    countBX += 1
  elif line[-1] == 'A':
    countXA += 1
  countAB += line.count('AB')

if countBXA > 0 and countBX == 0 and countXA == 0:
  countAB += countBXA - 1
else:
  countAB += min(countBX, countXA) + countBXA

print(countAB)

Submission status: Accepted

Solution code:
import re

class Solver:
    def __init__(self, num):
        self.n = num
        self.ans = 0

        # Case 0: 文字列中にABが含まれている
        self.case_0 = 0

        # Case 1: 文字列が"B***A"
        self.case_1 = 0

        # Case 2: 文字列が"B***-"
        self.case_2 = 0

        # Case 3: 文字列が"-***A"
        self.case_3 = 0

        # Case 4: 文字列が"-***-"
        # そもそもカウントする必要がない
        # self.case_4 = 0

        self.solve()
    
    def solve(self):
        for i in range(self.n):
            sen = input()
            if sen.find("AB") != -1:
                for m in re.finditer(r"AB", sen):
                    self.case_0 = self.case_0 + 1
            if sen[0] == "B" and sen[-1] == "A":
                self.case_1 = self.case_1 + 1
            elif sen[0] == "B" and sen[-1] != "A":
                self.case_2 = self.case_2 + 1
            elif sen[0] != "B" and sen[-1] == "A":
                self.case_3 = self.case_3 + 1
    

        if self.case_1 == 0:
            self.ans = self.ans + min(self.case_3, self.case_2)
        else:
            if self.case_3 + self.case_2 > 0:
                self.ans = self.ans + self.case_1 + min(self.case_3, self.case_2)
            elif self.case_3 + self.case_2 == 0:
                self.ans = self.ans + self.case_1 - 1

        self.ans = self.ans + self.case_0

        print(str(self.ans))

def main():
    n=int(input())
    Solver(n)



if __name__ == "__main__":
    main()

Submission status: Accepted

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

a = b = ab = t = 0
for s in S:
	if s[0] == "B" and s[-1] == "A":
		ab += 1
	elif s[0] == "B":
		b += 1
	elif s[-1] == "A":
		a += 1
	t += s.count("AB")
	#3
t += max(0,ab - 1)
if ab > 0:
	#2
	if a > 0:
		t += 1
		a -= 1
	if b > 0:
		t += 1
		b -= 1
#1
t += min(a,b)
print(t)

Submission status: Accepted

Solution code:
read = input
n = int(read())
ans = 0
B = 0
A = 0
BA = 0
for i in range(n):
    s = read()
    ans += s.count("AB")
    if s[0] == 'B' and s[-1] == 'A': BA += 1
    elif s[0] == 'B':B += 1
    elif s[-1] == 'A':A += 1
#关键在于分类，选分类选取BA，因为A，B是对称的
if BA == 0:
    ans += min(A,B)
else  :
    if A + B == 0:
        ans += BA - 1
    else :
        ans += BA + min(A,B)
print(ans)

Submission status: Accepted

Solution code:
n = int(input())

ans, tailA, headB, overlap = 0, 0, 0, 0
for _ in range(n):
    s = input()
    ans += s.count('AB')
    tailA += 1 * (s[-1] == 'A')
    headB += 1 * (s[0] == 'B')
    overlap += 1 * (s[-1] == 'A' and s[0] == 'B')

if overlap > 0:
    tailA -= overlap
    headB -= overlap
    ans += overlap - 1
    if tailA > 0:
        ans += 1
        tailA -= 1
    if headB > 0:
        ans += 1
        headB -= 1

ans += min(tailA, headB)
print(ans)

Submission status: Accepted

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

n = int(input())
a = 0
b = 0
ba = 0
ans = 0

for i in range(n):
  s = input().strip()
  leng = len(s)
  if s[0] == 'B' and s[-1] == 'A':
    ba += 1
    a += 1
    b += 1
  elif s[-1] == 'A':
    a += 1
  elif s[0] == 'B':
    b += 1
  for j in range(leng - 1):
    if s[j] == 'A' and s[j+1] == 'B':
      ans += 1

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

Submission status: Accepted

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

n = int(input())
a = 0
b = 0
ba = 0
ans = 0

for i in range(n):
  s = input().strip()
  leng = len(s)
  if s[0] == 'B' and s[-1] == 'A':
    ba += 1
    #a += 1
    #b += 1
  elif s[-1] == 'A':
    a += 1
  elif s[0] == 'B':
    b += 1
  for j in range(leng - 1):
    if s[j] == 'A' and s[j+1] == 'B':
      ans += 1

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

Submission status: Accepted

Solution code:
from sys import exit

N = int(input())

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

count = 0
a_count = 0
b_count = 0
a_b_count = 0

for s in S:
	if s[0] == 'B' and not s[-1] == 'A':
		b_count += 1
	if not s[0] == 'B' and s[-1] == 'A':
		a_count += 1
	if s[0] == 'B' and s[-1] == 'A':
		a_b_count += 1
	for i in range(len(s) - 1):
		if s[i] == 'A':
			if s[i + 1] == 'B':
				count += 1

if a_b_count == 0:
	print(count + min(a_count, b_count))
else:
	if not (a_count == 0 and b_count == 0):
		a_count += 1
		b_count += 1
	print(count + min(a_count, b_count) + a_b_count - 1)

Submission status: Accepted

Solution code:
N = int(input())
c1 = 0
c2 = 0
c3 = 0
count = 0
for i in range(N):
  s = input()
  count += s.count('AB')
  if s[0] == 'B' and s[-1] == 'A':
    c1 += 1
  elif s[0] == 'B' and s[-1] != 'A':
    c2 += 1
  elif s[0] != 'B' and s[-1] == 'A':
    c3 += 1
  else:
    pass

if c1 == 0:
  print(count + min(c2,c3))
else:
  if c2 > 0 or c3 > 0:
    print(count + c1 + min(c2,c3))
  else:
    print(count + c1-1)

Submission status: Accepted

Solution code:
import sys,heapq
from collections import deque,defaultdict
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
DBG = True  and False
def ddprint(x):
  if DBG:
    print(x)

ab = 0
leftb = 0
righta = 0
lbra = 0
n = inn()
for i in range(n):
    s = input()
    if s[0] == 'B' and s[-1] == 'A':
        lbra += 1
    if s[0] == 'B':
        leftb += 1
    if s[-1] == 'A':
        righta += 1
    for j in range(len(s)-1):
        if s[j:j+2] == 'AB':
            ab += 1

if DBG:
    print("ab {} l {} r {} lbra {} ".format(ab, leftb, righta, lbra))
print(ab + (max([0,lbra-1]) if lbra==leftb and leftb==righta else min([leftb, righta])))

Submission status: Accepted

Solution code:
N = int(input())
inside_str = 0
tail_a = 0
head_b = 0
 
doubleAB = 0
 
for i in range(N):
  str = input()
  inside_str = inside_str + str.count('AB')
  
  if(str[-1] == 'A' and str[0] == 'B'):
  	doubleAB = doubleAB + 1
  elif (str[-1] == 'A'):
    tail_a = tail_a + 1
  elif (str[0] == 'B'):
    head_b = head_b + 1
 
if(tail_a == 0 and head_b == 0):
  if(doubleAB == 0):
    total_cand = inside_str
  else:
    total_cand = inside_str + doubleAB - 1
else:
  total_cand = inside_str + doubleAB + min(tail_a, head_b)

print(total_cand)