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:
import sys

def inp():
  return sys.stdin.readline().strip()

N = int(inp())
inAB = 0
sB = 0
eA = 0
both = 0
for _ in range(N):
  s = inp()
  inAB += s.count('AB')
  if s[0] == 'B' and s[-1] == 'A':
    both += 1
    continue
  if s[0] == 'B':
    sB += 1
  if s[-1] == 'A':
    eA += 1

pair = min(eA, sB)
if sB > 0 or eA > 0:
  ans = both + pair
else:
  ans = both - 1
print(inAB + max(ans, 0))

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
n=int(input())
ans=0
d={"a":0,"b":0,"w":0}
for i in range(n):
    s=input()
    if s[0]=="B" and s[-1]=="A": d["w"]+=1
    elif s[0]=="B" : d["b"]+=1
    elif s[-1]=="A" : d["a"]+=1
    ans+=s.count("AB")
if d["a"]==0 and d["w"]>0:
    d["a"]=1
    d["w"]-=1
if d["w"]>0:
    ans+=d["w"]
    d["w"]=0
    d["a"]-=1
    if d["b"]>0:
        ans+=1
        d["b"]-=1
ans+=max(0,min(d["a"],d["b"]))
print(ans)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

N = INT()
num_either = 0
num_A = 0
num_B = 0

count = 0
for _ in range(N):
	s = input()
	if s[-1] == "A" and s[0] == "B":
		num_either += 1
	elif s[-1] == "A":
		num_A += 1
	elif s[0] == "B":
		num_B += 1

	for i, char in enumerate(s):
		if i == len(s)-1:
			break
		if s[i] == "A" and s[i+1] == "B":
			count += 1

if num_either >= 2:
	count += num_either-1
	num_either = 1
if num_A == 0 and num_B == 0:
	print(count)
else:
	if num_either == 1:
		count += min(num_A, num_B)+1
		print(count)
	else:
		count += min(num_A, num_B)
		print(count)

Submission status: Accepted

Solution code:
N=int(input())
both=0
one_A=0
one_B=0
sum=0
for i in range(N):
    S=list(input())
    if S[0]=='B' and S[len(S)-1]=='A':
        both+=1
    elif S[0]=='B':
        one_B+=1
    elif S[len(S)-1]=='A':
        one_A+=1
    for i in range(1,len(S)-1):
        if  S[i-1]=='A'and S[i]=='B':
            sum+=1
if both>0:
    sum+=(both-1)
    if one_A>0:
        sum+=1
        one_A-=1
    if one_B>0:
        sum+=1
        one_B-=1
    if one_A>one_B:
        sum+=one_B
    else:
        sum+=one_A
else:
    if one_A>one_B:
        sum+=one_B
    else:
        sum+=one_A
print(sum)

Submission status: Accepted

Solution code:
n=int(input())
s=[input() for _ in range(n)]
a=[]
b=[]
ab=[]
c=[]
for t in s:
    if t[0]=="B" and t[-1]=="A":
        ab.append(t)
    elif t[-1]=="A":
        a.append(t)
    elif t[0]=="B":
        b.append(t)
    else:
        c.append(t)
        
res=[]
ta,tb=0,0
if len(a)>0:
    res.append(a[ta])
    ta+=1
for t in ab:
    res.append(t)
if len(b)>0:
    res.append(b[tb])
    tb+=1

while(len(a)>ta and len(b)>tb):
    res.append(a[ta])
    res.append(b[tb])
    ta+=1
    tb+=1
for i in range(ta,len(a)):
    res.append(a[i])
for i in range(tb,len(b)):
    res.append(b[i])

for t in c:
    res.append(t)
ans="".join(res)
j= ans[0]=="A"
count=0
for i in range(1,len(ans)):
    if j:
        if ans[i]=="A":
            j=True
        elif ans[i]=="B":
            j=False
            count+=1
        else:
            j=False
    else:
        if ans[i]=="A":
            j=True
        else:
            j=False
print(count)

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

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

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

ans = 0

x = y = z = 0

for si in s:
    # 内部のABカウント
    ans += si.count('AB')

    # 右端A かつ 左端B ... Z
    if si[:1] == 'B' and si[-1:] == 'A':
        z += 1

    # 右端A ... X
    elif si[-1:] == 'A':
        x += 1

    # 左端B ... Y
    elif si[:1] == 'B':
        y += 1

if z <= x and z <= y:
    ans += 2*z
    ans += min(x,y) - z

else:
    ans += min(z, x)
    ans += min(z, y)

    if z >= x and z >= y:
        if x == 0 and y == 0:
            ans += z-1
        else:
            ans += z - max(x,y)

print(ans)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    strings = []
    for i in range(N):
        strings.append(input())
    
    ab = 0
    back_a = 0
    front_b = 0
    back_a_front_b = 0
    others = 0
    for i in strings:
        tmp = i
        ret = tmp.find("AB")
        while ret>=0:
            ab += 1
            tmp = tmp[ret+1:]
            ret = tmp.find("AB")
        
        if i[0] =="B" and i[-1]=="A":
            back_a_front_b += 1
        elif i[0] == "B":
            front_b += 1
        elif i[-1] == "A":
            back_a += 1
        else:
            others += 1

    if back_a_front_b == 0:
        print(ab + min([front_b,back_a]))
    elif back_a_front_b == N:
        print(ab + back_a_front_b -1)
    elif  min([front_b,back_a]) > 0:
        print(ab + back_a_front_b + 1 + min([front_b-1,back_a-1]))
    else:
        if back_a == 0 and front_b == 0:
            print(ab + max([back_a_front_b -1, 0]))
        elif back_a == 1 and front_b == 1:
            print(ab + back_a_front_b + 1)
        else:
            print(ab + back_a_front_b)

    #print("\n" + str(ab))
    #print(back_a_front_b)
    #print(back_a)
    #print(front_b)

if __name__ == "__main__":
    main()

Submission status: Accepted

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

tail_a_num = 0
head_b_num = 0
both_num = 0
cnt = 0
for i in s:
  if i[0] == 'B':
    head_b_num += 1
  if i[-1] == 'A':
    tail_a_num += 1
  if i[0] == 'B' and i[-1] == 'A':
    both_num += 1
  cnt += i.count('AB')

if both_num > 0:
  cnt += both_num - 1
  head_b_num -= both_num
  tail_a_num -= both_num
  if head_b_num > 0:
    cnt += 1
    head_b_num -= 1
  if tail_a_num > 0:
    cnt += 1
    tail_a_num -= 1

cnt += min(head_b_num,tail_a_num)
  
print(cnt)

Submission status: Accepted

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

if N == 1:
    print(S[0].count("AB"))
    quit()

ba, ab, a, b = 0, 0, 0, 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
    ab += s.count("AB")

if ba == 0:
    print(ab + min(a, b))
    quit()

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

Submission status: Accepted

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

sBA = [ss for ss in s if ss[0] == 'B' and ss[-1] == 'A']
sXA = [ss for ss in s if ss[0] != 'B' and ss[-1] == 'A']
sBX = [ss for ss in s if ss[0] == 'B' and ss[-1] != 'A']
sXX = [ss for ss in s if ss[0] != 'B' and ss[-1] != 'A']

ans = sXX
if sXA:
    ans.append(sXA.pop())
ans.extend(sBA)
while sXA or sBX:
    if sBX:
        ans.append(sBX.pop())
    if sXA:
        ans.append(sXA.pop())

#print(ans)

ans = ''.join(ans)

nans = 0
for i in range(len(ans) - 1):
    if ans[i] == 'A' and ans[i+1] == 'B':
        nans += 1

print(nans)

Submission status: Accepted

Solution code:
x = int(input())
a = 0
b = 0
c = 0
f = 0
bun = []
for p in range(x):
    bun = input()
    if bun[0] == "B":
        b +=1
    if bun[len(bun)-1] == "A":
        a += 1
        if bun[0] == "B":
            f += 1
    for k in range(len(bun)-1):
        if bun[k] == "A":
            if bun[k+1] == "B":
                c += 1



if f == a:
    if a == b:
        if a > 0:
            a -= 1
if a < b:
    print(a+c)
else:
    print(b+c)

Submission status: Accepted

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

ans = 0
n_a = 0
n_b = 0
n_ab = 0
A_count = 0
B_count = 0
for i in range(N):
	ans += s[i].count("AB")
	if s[i][0] == "B" and s[i][-1] == "A":
		n_ab += 1
	if s[i][0] == "B" and s[i][-1] != "A":
		n_b += 1
	if s[i][0] != "B" and s[i][-1] == "A":
		n_a += 1
if n_ab == 0:
	ans += min(n_a,n_b)
if n_ab != 0:
	ans += n_ab-1
	if n_a == 0 and n_b == 0:
		ans += 0
	if n_a == 0 and n_b != 0:
		ans += 1
	if n_a != 0 and n_b == 0:
		ans += 1
	if n_a != 0 and n_b != 0:
		ans += 2+min(n_a-1,n_b-1)

print(ans)

Submission status: Accepted

Solution code:


def read_input():
    n = int(input())
    slist = []
    for i in range(n):
        slist.append(input())

    return n, slist

def submit():
    n, slist = read_input()

    ab_in = 0
    x_a = 0
    b_x = 0
    b_a = 0

    for s in slist:
        for s1,s2 in zip(s, s[1:]):
            if s1 == 'A' and s2 == 'B':
                ab_in += 1

        if s[0] == 'B' and s[-1] == 'A':
            b_a += 1
        elif s[0] == 'B':
            b_x += 1
        elif s[-1] == 'A':
            x_a += 1

    chain_ab = 0

    # b_aをつなげる
    if b_a > 0:
        chain_ab += b_a - 1
        if x_a > 0:
            chain_ab += 1
            x_a -= 1

        if b_x > 0:
            chain_ab += 1
            b_x -= 1

    print(ab_in + chain_ab + min(x_a, b_x))


if __name__ == '__main__':
    submit()

Submission status: Accepted

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

b_head_a_tail = 0
b_head = 0
a_tail = 0

for _ in range(N):
    string= input()
    if string[0] == "B":
        if string[-1] == "A":
            b_head_a_tail += 1
        else:
            b_head += 1
    elif string[-1] == "A":
        a_tail += 1
    if "AB" in string:
        ans += string.count("AB")
        
if b_head_a_tail > 0:
    if a_tail > 0:
        if b_head > 0:
            ans += b_head_a_tail  + min(a_tail, b_head) 
        else:
            ans += b_head_a_tail
    else:
        if b_head > 0:
            ans += b_head_a_tail
        else:
            ans += b_head_a_tail - 1
else:
    ans += min(a_tail, b_head) 
    
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = [input() for _ in range(n)]
start_b = len([i for i in s if i[0] == "B" and i[-1] != "A"])
end_a = len([i for i in s if i[-1] == "A" and i[0] != "B"])
both = len([i for i in s if i[0] == "B" and i[-1] == "A"])
include_ab = sum([i.count("AB") for i in s])

if both:
  if end_a:
    if start_b:
      end_a -= 1
      start_b -= 1
      include_ab += (both+1)
    else:
      end_a -= 1
      include_ab += both
  else:
    if start_b:
      start_b -= 1
      include_ab += both
    else:
      include_ab += (both - 1)
print(include_ab + min(start_b,end_a))

Submission status: Accepted

Solution code:
import re

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

num_end_with_A = 0
num_start_with_B = 0
num_both = 0
num_inner_AB = 0

for ss in s:
    res = re.findall('AB', ss)
    if res:
        num_inner_AB += len(res)
    if ss[0] == 'B' and ss[-1] == 'A':
        num_both += 1
    elif ss[0] == 'B':
        num_start_with_B += 1
    elif ss[-1] == 'A':
        num_end_with_A += 1

if num_end_with_A == 0 and num_start_with_B == 0:
    print(num_inner_AB + max(num_both - 1, 0))
else:
    print(num_inner_AB + min(num_end_with_A, num_start_with_B) + num_both)

Submission status: Accepted

Solution code:
N = int(input())
S = []
for _ in range(N):
  S.append(input())
ans = 0
tailA, headB, b_a = 0, 0, 0
for s in S:
  ans += s.count('AB')
  h, t = s[0], s[-1]
  if h == 'B' and t != 'A':
    headB += 1
  elif h != 'B' and t == 'A':
    tailA += 1
  elif h == 'B' and t == 'A':
    b_a += 1
ans += min(tailA, headB)
if b_a > 0:
  ans += b_a - 1
  if tailA > 0 or headB > 0:
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline

N = int(readline())
S_list = [readline().rstrip() for i in range(N)]

count = 0
head_B = 0
tail_A = 0
AxB = 0
for s in S_list:
    for i in range(len(s)):
        if s[i:i+2] == 'AB':
            count += 1
    if s[0] == 'B':
        head_B += 1
    if s[-1] == 'A':
        tail_A += 1
    if (s[0] == 'B') != (s[-1] == 'A'):
        AxB += 1

if head_B == tail_A:
    if AxB > 0:
        print(count + head_B)
    else:
        print(count + max(head_B - 1, 0))
else:
    print(count + min(head_B, tail_A))

Submission status: Accepted

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

def solve():
    N = int(input())
    ans = 0
    endA = 0
    startB = 0
    ryouhou = 0
    # Aで終わるs1と、Bで始まるs2を連結させれば1個増える
    for i in range(N):
        s = input()
        if s[-1]=="A" and s[0]=="B":
            ryouhou += 1
        elif s[-1]=="A":
            endA += 1
        elif s[0]=="B":
            startB += 1
        
        ans += s.count("AB")
    

    if endA>=1 and startB>=1 and ryouhou>=1:
        ans += min(endA-1, startB-1)
        ans += ryouhou + 1
        print(ans)
        return
    elif ((endA>=1 and startB==0 and ryouhou>=1) or
          (endA==0 and startB>=1 and ryouhou>=1)):
        ans += ryouhou
        print(ans)
        return
    elif endA==0 and startB==0 and ryouhou>=1:
        ans += ryouhou-1
        print(ans)
        return
    else:
        # ryouhou==0のとき
        ans += min(endA, startB)
        rest = abs(max(endA, startB) - min(endA, startB))
        
        ans += min(rest, ryouhou)
        rest = ryouhou - rest
        if rest <= 0:
            print(ans)
            return
        else:
            ans += rest//2
            print(ans)
            return

if __name__ == "__main__":
    solve()

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def solve():
    ans = 0
    li = [0, 0, 0, 0]
    for _ in range(int(input())):
        s = input()
        ans += s.count("AB")
        flg = 0
        if s[0] == 'B':
            flg = 1
        if s[-1] == 'A':
            flg += 2
        li[flg] += 1
    if li[3] > 0:
        if li[1] > 0:
            ans += 1
            li[1] -= 1
        if li[2] > 0:
            ans += 1
            li[2] -= 1
        ans += li[3] - 1
    print(ans + min(li[1], li[2]))
solve()

Submission status: Accepted

Solution code:
N = int(input())
s = 0
t = 0
u = 0
v = 0
for i in range(N):
    m = input()
    u += m.count("AB")
    if m[0] == "B" and m[-1] == "A":
        v += 1
    else:
        if m[0] == "B":
            s += 1
        if m[-1] == "A":
            t += 1
if s == 0 and t == 0 and v != 0:
    u += v - 1
    print(u)
elif s == 0 or t == 0:
    u += v
    print(u)
else: 
    u += min(s - 1, t - 1) + v + 1
    print(u)

Submission status: Accepted

Solution code:
import re
N = int(input())
S = [input() for i in range(N)]
nAB = sum(map(lambda x: x.count('AB'), S))
lastB = sum(map(lambda x: x[0] == 'B', S))
firstA = sum(map(lambda x: x[-1] == 'A', S))
matchAB = sum(map(lambda x: x[0] == 'B' and x[-1] == 'A', S))
if min(lastB, firstA) == 0:
    print(nAB)
elif lastB == firstA and matchAB - min(lastB, firstA) == 0:
    print(nAB+min(lastB, firstA)-1)
elif matchAB - min(lastB, firstA) == 0:
    print(nAB+min(lastB, firstA))
else:
    print(nAB+min(lastB, firstA))

Submission status: Accepted

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


def solve(N: int, s: "List[str]"):
    count_AB = 0
    count_endswith_A = 0
    count_startswith_B = 0
    count_BA = 0
    for ss in s:
        count_AB += ss.count('AB')
        if ss.endswith('A') and ss.startswith('B'):
            count_BA += 1
            continue
        if ss.endswith('A'):
            count_endswith_A += 1
        if ss.startswith('B'):
            count_startswith_B += 1
    count_pair = min(count_endswith_A, count_startswith_B)
    if count_pair > 0:
        print(count_AB + count_pair + count_BA)
    elif count_endswith_A > 0 or count_startswith_B > 0:
        print(count_AB + count_BA)
    elif count_BA > 0:
        print(count_AB + count_BA - 1)
    else:
        print(count_AB)
    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:
inpl = lambda: list(map(int,input().split()))
N = int(input())
ans = 0
BA  = [[0, 0], [0, 0]]
for i in range(N):
    s = input()
    ans += s.count('AB')
    h = 1 if s[0]=='B' else 0
    t = 1 if s[-1]=='A' else 0
    BA[h][t] += 1
if BA[1][0]==BA[0][1]==0 and BA[1][1]>0:
    ans += BA[1][1]-1
else:
    ans += min(BA[1][0],BA[0][1]) + BA[1][1]

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
P = 0
K = 0
L = 0
ans = 0
for _ in range(N):
  s = input()
  lis = []
  for i in range(len(s) - 1):
    lis.append(s[i:i+2])
    num = lis.count("AB")
  ans += num
  if s[0] == "B" and s[-1] == "A":
    P += 1
  elif s[0] == "B":
    K += 1
  elif s[-1] == "A":
    L += 1
if P >= 1:
  ans += (P - 1)
  if K > 0 and L > 0:
    ans += 2
    ans += min(K -1, L - 1)
  elif K > 0 and L == 0:
    ans += 1
  elif K == 0 and L > 0:
    ans += 1
else:
  ans += min(K, L)
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = [input() for _ in range(N)]
first_c = []
last_c = []
XA = 0
BA = 0
BX = 0

ans = 0

for s in S:
    first_c.append(s[0])
    last_c.append(s[len(s)-1])
    ans += s.count("AB")

for i in range(len(S)):
    if first_c[i] == "B" and last_c[i] == "A":
        BA += 1
    elif first_c[i] == "B" and last_c[i] != "A":
        BX += 1
    elif first_c[i] != "B" and last_c[i] == "A":
        XA += 1

if BX > 0 and XA > 0:
    ans += min(BX, XA) + BA
elif BX > 0 or XA > 0:
    ans += BA
elif BA > 1:
    ans += BA-1

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
count=0
A = 0
B = 0
BA = 0
for i in range(N):
  s = input()
  exist = 0
  if (s[0] == 'B') and (s[-1] == 'A'):
    BA +=1
  elif s[0] == 'B':
    B+=1
  elif s[-1:] == 'A':
    A+=1
  for j in range(len(s)-1):
    if s[j:j+2] == "AB":
      count+=1
#print(A,B,BA,count)

if BA > 1:
  count += BA - 1
if BA >0:
  if A > 0 :
    count +=1
    A-=1
  if B>0:
    count+=1
    B-=1
if A>B:
  count += B
else:
  count += A
print(count)

Submission status: Accepted

Solution code:
N = int(input())
a = 0  # Aで終了
b = 0  # Bで開始
ab = 0 # Aで終了, Bで開始
ans = 0
for _ in range(N):
    s = input()
    ans += s.count('AB')
    if s[0] == 'B':
        b += 1
        if s[-1] == 'A':
            a += 1
            ab += 1
    elif s[-1] == 'A':
        a += 1
if a == b == ab:
    if a == 0:
        print(ans)
    else:
        print(ans + a - 1)
else:
    print(ans + min(a, b))

Submission status: Accepted

Solution code:
from collections import defaultdict
from string import ascii_uppercase
import sys, bisect, math
stdin = sys.stdin
read_int = lambda : list(map(int,stdin.readline().split()))
read_str = lambda : stdin.readline().rstrip()

N = read_int()[0]
S = [read_str() for _ in range(N)]

def solve():
    _a = 0
    b_ = 0
    ba = 0
    in_ab = 0

    # search
    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
        for j in range(len(S[i]) - 1):
            if S[i][j: j + 2] == 'AB':
                in_ab += 1

    ans = 0
    if ba == 0:
        ans += in_ab + min(_a, b_)
        return ans
    ans += in_ab + max(ba - 1,0) + max(0, min(_a - 1, b_ - 1))
    # print(in_ab, ba, ans)
    if _a > 0: ans += 1
    if b_ > 0: ans += 1
    return ans

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
n = int(input())

cnt_ab = 0
cnt_ba = 0
cnt_last_a = 0
cnt_first_b = 0
for _ in range(n):
    s = input()
    cnt_ab += s.count("AB")

    b_flag, a_flag = False, False
    if s[0] == 'B':
        b_flag = True
    if s[-1] == 'A':
        a_flag = True

    if a_flag and b_flag:
        cnt_ba += 1
    elif b_flag:
        cnt_first_b += 1
    elif a_flag:
        cnt_last_a += 1

if cnt_ba >= 2:
    cnt_ab += cnt_ba - 1
    cnt_ba = 1

if cnt_ba == 1 and cnt_first_b >= 1 and cnt_last_a >= 1:
    cnt_ab += 2
    cnt_first_b -= 1
    cnt_last_a -= 1
elif cnt_ba == 1:
    if max(cnt_first_b, cnt_last_a) > 0:
        cnt_ab += 1

print(cnt_ab + min(cnt_first_b, cnt_last_a))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = int(input())

ans = 0
A_flag = 0
B_flag = 0
A_flag2 = 0
B_flag2 = 0

for i in range(N):
    S = input()
    ans += S.count('AB')

    if S[0] == 'B':
        B_flag += 1

    if S[-1] == 'A':
        A_flag += 1

    if S[0] != 'B' and S[-1] == 'A':
        A_flag2 = 1

    if S[0] == 'B' and S[-1] != 'A':
        B_flag2 = 1

if A_flag != B_flag:
    ans += min(A_flag,B_flag)
else:
    if A_flag+B_flag != 0:
        if A_flag2*B_flag2 == 0:
            ans += min(A_flag,B_flag) -1
        else:
            ans += min(A_flag,B_flag)
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# coding:utf-8


def main():
    N = int(input())
    s_list = []
    for i in range(N):
        s_list.append(input().rstrip())

    ans = 0
    a_last = 0
    ab_count = 0
    b_start = 0
    for si in s_list:
        if si[0] == "B" and si[-1] == "A":
            ab_count += 1
        elif si[0] == "B":
            b_start += 1
        elif si[-1] == "A":
            a_last += 1

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

    if ab_count > 0:
        ans += ab_count - 1
        if a_last == 0 and b_start == 0:
            pass
        else:
            ans = ans + min(a_last, b_start) + 1
    else:
        ans = ans + min(a_last, b_start)
    # print(ab_count, a_last, b_start)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 20:47:47 2019

@author: Owner
"""

# -*- coding: utf-8 -*-
"""
Created on Sat Apr 13 09:53:12 2019

@author: Owner
"""
import numpy as np
import sys
import collections
import scipy.misc
import math
from operator import itemgetter
import itertools
import copy
import bisect

#素因数を並べる
def prime_decomposition(n):
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n /= i
      table.append(int(i))
    i += 1
  if n > 1:
    table.append(int(n))
  return table   
# 桁数を吐く
def digit(i):
    if i > 0:
        return digit(i//10) + [i%10]
    else:
        return []
    
def getNearestValueIndex(list, num):
    """
    概要: リストからある値に最も近い値のインデックスを取得する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return idx

def find_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default


"""
N, X = map(int, input().split())

x = list(map(int, input().split()))

P = [0]*N
Y = [0]*N
for n in range(N):
    P[n], Y[n] = map(int, input().split())

# 多次元配列の宣言（あとでintにすること。）（タプルにすること。）
dp = np.zeros((N+1, 4,4,4))
    
all(nstr.count(c) for c in '753')

# 複数配列を並び替え
ABT = zip(A, B, totAB)
result = 0
# itemgetterには何番目の配列をキーにしたいか渡します
sorted(ABT,key=itemgetter(2))
A, B, totAB = zip(*ABT)
A.sort(reverse=True)

# 2進数のbit判定
(x >> i) & 1

# dp最小化問題
dp = [np.inf]*N
for n in range(N):
    if n == 0:
        dp[n] = 0
    else:
        for k in range(1,K+1):
            if n-k >= 0:
                dp[n] = min(dp[n], dp[n-k] + abs(h[n]-h[n-k]))
            else:
                break
# 累積和
add = 1 # 問題によって決まる
res = 0
sums = [0]*(len(nums)+1)
for i in range(len(nums)):
    sums[i+1] = sums[i] + nums[i]
for i in range(0, len(nums), 2):
    left = i
    right = min(i+add, len(nums))
    tmp = sums[right] - sums[left]
    res = max(tmp, res)

#２分探索
li, ri = bisect.bisect_left(p_ac, l[i]-1), bisect.bisect_right(p_ac, r[i]-1)    

#ソート関数
org_list = [3, 1, 4, 5, 2]
new_list = sorted(org_list)
print(org_list)
print(new_list)
# [3, 1, 4, 5, 2]
# [1, 2, 3, 4, 5]

"""
N = int(input())

s = [""]*N

cnt  = 0
cnt_A= 0
cnt_B= 0
cnt_BA=0
for n in range(N):
    s[n] = input()
    cnt += s[n].count("AB")
    if s[n][0] == "B" and s[n][-1] == "A":
        cnt_BA+=1
        continue
    elif s[n][0]=="B":
        cnt_B +=1
    elif s[n][-1]=="A":
        cnt_A +=1
    else:
        pass
    
            

def main(): 
    #print(s, cnt)
    if cnt_A == 0 and cnt_B ==0:
        if cnt_BA ==0:
            print(cnt)
        else:
            print(cnt + cnt_BA-1)
    else:
        print(cnt + min(cnt_BA+cnt_B, cnt_BA+cnt_A))
                
                
                
            
            
                

    
if __name__ == '__main__':
    main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#
import itertools
from collections import Counter
from collections import defaultdict
import bisect

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

    top_B = 0
    tail_A = 0
    both = 0
    for _ in range(N):
        s = input()
        inside += s.count('AB')
        if s[0] == 'B' and s[-1] == 'A':
            both += 1
        else:
            if s[0] == 'B':
                top_B += 1
            elif s[-1] == 'A':
                tail_A += 1
    # print('inside = {}, top b = {}, tail a = {}, both = {}'.format(inside, top_B, tail_A, both))
    ans = inside

    if both > 1:
        ans += (both - 1)
        both = 1

    if both > 0:
        if tail_A == 0:
            tail_A += 1
            both -= 1
        if top_B == 0 and both > 0:
            top_B += 1
            both -= 1

    while both > 0 and top_B > 0 and tail_A > 0:
        ans += 2
        both -= 1
        tail_A -= 1
        top_B -= 1

        if both > 0:
            if tail_A == 0:
                tail_A += 1
                both -= 1
        if both > 0:
            if top_B == 0:
                top_B += 1
                both -= 1

    ans += min(top_B, tail_A)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())
count_A_right = 0
count_B_left  = 0
AB_count = 0
same_count = 0

for _ in range (N):
    S = input()
    temp = 0
    if S[0] == 'B':
        count_B_left +=1
        temp +=1
    if S[-1] == 'A':
        count_A_right +=1
        temp +=1
    if temp ==2:
        same_count+=1
        count_A_right -=1
        count_B_left  -=1
    for i in range (len(S)-1):
        if S[i:i+2] == 'AB':
            AB_count +=1

if same_count-1>=0:
    AB_count += same_count-1#一つのBAに変更して加える
    count_A_right +=1
    count_B_left  +=1
    if count_A_right==1 and count_B_left ==1:
        print(AB_count)
    else:
        print(AB_count+min(count_A_right,count_B_left))
else:
    print(AB_count+min(count_A_right,count_B_left))