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: Wrong Answer

Solution code:
N = int(input())
s = [input() for _ in range(N)]
numAB = 0
numBonly = 0
numAonly = 0
numAandB = 0

for i in s:
    numAB += i.count("AB")
    if i[0] == 'B' and i[-1] != 'A':
        numBonly += 1
    elif i[0] != 'B' and i[-1] == 'A':
        numAonly += 1
    elif i[0] == 'B' and i[-1] == 'A':
        numAandB += 1

if numAonly == numBonly:
    print(numAB + numAonly + max(0, numAandB - 1))
else:
    print(numAB + min(numAonly, numBonly) + numAandB)

Submission status: Wrong Answer

Solution code:
n=int(input())
ans=0
flagA=0
flagB=0
for x in range(n):
    s = input()
    if 'AB' in s:
        ans += 1
    if s[-1]=='A':
        flagA += 1
    if s[0]=='B':
        flagB += 1
ans+=min(flagA,flagB)
print(ans)

Submission status: Wrong Answer

Solution code:
#python 3.5.2

N = int(input())
s_list = [input() for i in range(N)]
cnt = sum([1 for s in s_list if "AB" in s])
a_end, b_start, a_b = 0, 0, 0
for s in s_list:
    if s[0] == "B" and s[-1] == "A":
        a_b += 1
    elif s[0] == "B":
        b_start += 1
    elif s[-1] == "A":
        a_end += 1
cnt += min(a_end, b_start)
sabun = abs(a_end - b_start)
if sabun >= a_b:
    cnt += a_b
else:
    cnt += sabun + int((a_b - sabun)/2) + 1
print(a_end, b_start, a_b)
print(cnt)

Submission status: Wrong Answer

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 + B_A - 1
    else:
        ret = has_AB + min(end_byA + B_A, start_byB + B_A)
    print str(ret)

if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
n = int(input())
words = [str(input()) for i in range(n)]
counter = 0
beginb = 0
enda = 0
mix = 0
for word in words:
    for index, letter in enumerate(word):
        if index<len(word)-1:
            if word[index] == 'A' and word[index+1] == 'B':
                counter += 1
    if word[0] == "B" and word[-1] == "A":
        mix += 1
    else:
        if word[0] == "B":
            beginb += 1
        if word[-1] == "A":
            enda += 1
diff = abs(beginb-enda)

if diff > mix:
    print(counter+min(beginb,enda)+mix)
else:
    newmix = (mix-diff)//2
    print(counter+max(beginb,enda)+newmix)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [input() for _ in range(N)]
ans = 0
a = 0
b = 0
ab = 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
    for i in range(len(s) - 1):
        if s[i:i+2] == "AB":
            ans += 1
if ab >= 1:
    ans += max(ab-1, 0)
    if a > 0 and b > 0:
        ans += 2
        a -= 1
        b -= 1
    else:
        if a > 0:
            ans += 1
            a = 0
        else:
            ans += 1
            b = 0
    """if a > b:
        b += 1
    elif a == b:
        a += 1
        b += 1
    else:
        a += 1"""
ans += min(a, b)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import Counter
from collections import deque
from functools import reduce
from pprint import pprint
# import statistics
import bisect
import copy
import fractions
import math
import random
import sys
import time
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def MI(): return map(int, sys.stdin.readline().split())
def II(): return int(sys.stdin.readline())
def IS(): return input()
def C(x): return Counter(x)
def GCD_LIST(numbers):
    return reduce(fractions.gcd, numbers)
def LCM_LIST(numbers):
    return reduce(LCM, numbers)
def LCM(m, n):
    return (m * n // fractions.gcd(m, n))
def unite(x, y):
    # それぞれのノードの根を求める
    x = root(x)
    y = root(y)
    if x == y:
        return
    # node[x]の根をyに変更する
    node[x] = y
def same(x,y): return bool(root(x) == root(y))
def root(x):
    if node[x] == x:  # xが根の場合
        return x
    else:
        node[x] = root(node[x])  # 経路圧縮
        return node[x]
def dfs(v):
    # ノードに訪れた
    visited[v] = True
    for v2 in range(n):
        if graph[v][v2] == False:  # そもそもvとv2が辺でつながっていない
            continue
        if visited[v2] == True:  # もう見た
            continue
        dfs(v2)

n = II()
s = [IS() for _ in range(n)]
cnt = 0
sentou_b = 0
ushiro_a = 0
ab = 0
for i in s:
    cnt += i.count('AB')
    if i[0] == 'B':
        sentou_b += 1
    if i[-1] == 'A':
        ushiro_a += 1
    if i[0] == 'B' and i[-1] == 'A':
        ab += 1
# print(cnt)
# print(sentou_b)
# print(ushiro_a)
# print(ab)
# print('===')
if ab > 0 and i[0] == 'B' and i[-1] == 'A':
    print(cnt+min(sentou_b, ushiro_a)-1)
else:
    print(cnt+min(sentou_b, ushiro_a))

Submission status: Wrong Answer

Solution code:
count = 0
N = int(input())

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

if a != 0 and b != 0:
  a_b_min = min(a, b)
  count += a_b_min

  count += min(a_b_min, ba)
elif ba < max(a, b):
  count += ba
  count += 1
elif ba > max(a, b):
  count += ba
print(count)

Submission status: Wrong Answer

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 == num_start_with_B:
    print(num_inner_AB + num_end_with_A + max(num_both - 1, 0))
else:
    print(num_inner_AB + min(num_end_with_A, num_start_with_B) + num_both)

Submission status: Wrong Answer

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

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

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

enda=0
startb=0
both=0
cntab=0
for i in range(N):
    if S[i].startswith('B') and S[i].endswith('A'):
        both+=1
    elif S[i].startswith('B'):
        startb+=1
    elif S[i].endswith('A'):
        enda+=1
    cntab+=S[i].count('AB')

mnab=min(enda, startb)
cntab+=mnab
if both!=0:
    enda-=mnab
    startb-=mnab
    mxab=max(enda, startb)
    if mxab==0:
        cntab+=both-1
    else:
        if mxab<=both:
            cntab+=mxab+(both-mxab)
        else:
            cntab+=both
print(cntab)

Submission status: Wrong Answer

Solution code:
n=int(input())
ls=[0]*n
for i in range(n):
    ls[i]=input()
numab=0
sA=0
sB=0
sBA=0
for i in range(n):
    sb=""
    for j in ls[i]:
        if sb=="A":
            if j=="B":
                numab+=1
        sb=j
    if ls[i][0]=="B":
        if ls[i][-1]=="A":
            sBA+=1
        else:
            sB+=1
    if ls[i][-1]=="A" and ls[i][0]!="B":
        sA+=1
ans=0
if sA!=0 and sB!=0:
    ans=sBA+1+min(sA-1,sB-1)
elif sA==0 and sB!=0:
    ans=sBA
elif sB==0 and sA!=0:
    ans=sBA
else:
    ans=sBA-1
ans+=numab
#print(numab,sB,sA,sBA)
print(ans if ans>0 else 0)

Submission status: Wrong Answer

Solution code:
N = int(input())
num_tail_A = 0
num_head_B = 0
count = 0
for i in range(N):
  s = input()
  count += s.count('AB')
  if(s[len(s)-1]  in 'A'):
    num_tail_A += 1
  if(s[0] in 'B'):
    num_head_B += 1

result = count + min(num_tail_A, num_head_B)

print(result)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = [input() for i in range(N)]
count = 0
l = []
a = 0
b = 0
ab = 0
for i in s:
  count+=i.count("AB")
for i in s:
  if list(i)[0] == "B" and list(i)[-1] != "A":
    l.append(i)
    b += 1
  elif list(i)[-1] == "A" and list(i)[0] != "B":
    l.append(i)
    a += 1
  elif list(i)[-1] == "A" and list(i)[0] == "B":
    l.append(i)
    ab += 1
count += min(a, b) + ab
print(count)

Submission status: Wrong Answer

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

cnt = 0
cntA = 0
cntB = 0
cntAB = 0

for s in S :
    for i in range(1, len(s)) :
        if s[i - 1] =='A' and s[i] == 'B':
            cnt += 1
    if s[0] == 'B' and s[len(s) - 1] == 'A':
        cntAB += 1
    elif s[0] == 'B' :
        cntB += 1
    elif s[len(s) - 1] == 'A' :
        cntA += 1

ans = min(cntA + cntAB, cntB + cntAB)
if ans == len(S) :
    ans -= 1
if ans == 1 :
    ans = 0
print(cnt + ans)

Submission status: Wrong Answer

Solution code:
n,*s=open(0)
a=b=c=d=0
for t in s:
    if t[-2]=='A'and t[0]=='B':
        d+=1
    elif t[-2]=='A':
        a+=1
    elif t[0]=='B':
        b+=1
    c+=t.count('AB')
ans=min(a,b)+c
dif=abs(a-b)
ans+=min(dif,d)
d-=min(dif,d)
print(ans+d)

Submission status: Wrong Answer

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:
  ans-=1
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())

moji_list = []
A_count = 0
B_count = 0
AB_count = 0

if N == 1:
    moji = input()
    print(moji.count('AB'))

else:
    for i in range(N):
        moji = input()
        if moji[0] == 'B':
            B_count += 1
        if moji[-1] == 'A':
            A_count += 1
        
        AB_count += moji.count('AB')

    if A_count == B_count:
        print(AB_count+B_count-1)

    elif A_count > B_count:
        print(AB_count+B_count)
    else:
        print(AB_count+A_count)

Submission status: Wrong Answer

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:
    ans = AB_in + m -1

else:
    ans = AB_in + mini

print(ans)

Submission status: Wrong Answer

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

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

if start == end:
    c += start
#    if flg:
#        c  -= 1
elif start > end:
    c += end
else:
    c += start
print(c)

Submission status: Wrong Answer

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


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

one=min(a,b)
two=0
if ba>0:
	two=ba-1

	if abs(a-b)>0:
		two=ba-1+1
print(one+two+count)

Submission status: Wrong Answer

Solution code:
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()

n = ni()
_anum = 0
b_num = 0
banum = 0
ct = 0
for i in range(n):
    st = input()
    ct += st.count('AB')
    if st.startswith('B'):
        if st.endswith('A'):
            banum += 1
        else:
            b_num += 1
    else:
        if st.endswith("A"):
            _anum += 1
if banum > 0:
    if _anum == b_num:
        print(ct + min(_anum, b_num) + (banum - 1))
    else:
        print(ct + min(_anum, b_num) + banum)
else:
    print(ct + min(_anum, b_num))

Submission status: Wrong Answer

Solution code:
n=int(input())
count=0
dual=0
startb=0
enda=0
for i in range(n):
    tmp=list(input())
    if tmp[0]=="B" and tmp[-1]=="A":
        #dual+=1
        startb+=1
        enda+=1
    elif tmp[0]=="B":
        startb+=1
    elif tmp[-1]=="A":
        enda+=1

    aflag=0
    for t in tmp:
        if aflag==1 and t=="B":
            count+=1
            aflag=0
        elif t=="A":
            aflag=1
        else:
            aflag=0
"""
while dual>0:
    if startb>enda:
        enda+=1
    else:
        startb+=1
    dual-=1
"""
count+=min(startb,enda)
print(count)

Submission status: Wrong Answer

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)
  else:
    ans += 1
else:
  ans += min(K, L)
print(ans)

Submission status: Wrong Answer

Solution code:
#C問題
N = int(input())
S = [input() for i in range(N)]
ans = 0
a_top_count = 0
b_top_count = 0
a_down_count = 0
b_down_count = 0
ans_1 = 0

for i in range(N):
    tmp = S[i].count("AB")
    ans += tmp
    if S[i][0] == "B":
        b_top_count += 1
    if S[i][-1] == "A":
        a_down_count += 1

ans_1+= min(b_top_count, a_down_count)
if ans_1>= N:
    ans_1 = N -1
    
print(ans + ans_1)

Submission status: Wrong Answer

Solution code:
N = int(input())
Ss=[input() for s in range(N)]
count = [s.count("AB") for s in Ss if "AB" in s]
headcount = len([s for s in Ss if s[0]=="B"])
outcount = len([s for s in Ss if s[-1]=="A"])
if min(headcount,outcount)==len(Ss):
    print(sum(count) + min(headcount, outcount)-1)
else:
    print(sum(count)+min(headcount,outcount))

Submission status: Wrong Answer

Solution code:
# https://qiita.com/_-_-_-_-_/items/34f933adc7be875e61d0
# abcde	s=input()	s='abcde'
# abcde	s=list(input())	s=['a', 'b', 'c', 'd', 'e']
# 5(1つだけ)	a=int(input())	a=5
# 1 2	| x,y = s_inpl()   |	x=1,y=2
# 1 2 3 4 5 ... n 　	li = input().split()	li=['1','2','3',...,'n']
# 1 2 3 4 5 ... n 　	li = inpl()	li=[1,2,3,4,5,...,n]
# FFFTFTTFF 　	li = input().split('T')	li=['FFF', 'F', '', 'FF']

# INPUT
# 3
# hoge
# foo
# bar
# ANSWER
# n=int(input())
# string_list=[input() for i in range(n)]

import math
import copy
from collections import defaultdict
from collections import Counter
from collections import deque
# 直積 A={a, b, c}, B={d, e}:のとき，A×B={(a,d),(a,e),(b,d),(b,e),(c,d),(c,e)}: product(A, B)
from itertools import product
# 階乗 P!: permutations(seq), 順列 {}_len(seq) P_n: permutations(seq, n)
from itertools import permutations
# 組み合わせ {}_len(seq) C_n: combinations(seq, n)
from itertools import combinations
from bisect import bisect_left, bisect_right
# import numpy as np

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

# 四方向: 右, 下, 左, 上
dy = [0, -1, 0, 1]
dx = [1, 0, -1, 0]

def i_inpl(): return int(input())
def s_inpl(): return map(int,input().split())
def l_inpl(): return list(map(int, input().split()))
INF = float("inf")

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

ab_cnt = 0
f_a_cnt = 0
f_b_cnt = 0
l_a_cnt = 0
l_b_cnt = 0
f_b_l_a_cnt = 0

for s_i in s:
    ab_cnt += s_i.count("AB")
    if s_i[0] == "A":
        f_a_cnt += 1
    elif s_i[0] == "B":
        f_b_cnt += 1
    if s_i[-1] == "A":
        l_a_cnt += 1
    elif s_i[-1] == "B":
        l_b_cnt += 1
    if s_i[-1] == "A" and s_i[0] == "B":
        f_b_l_a_cnt += 1

print(ab_cnt + min(min(f_b_cnt, l_a_cnt), f_b_l_a_cnt-1))

Submission status: Wrong Answer

Solution code:
n = int(input())

s = []

ans = 0

both = 0
a_a = 0
b_a = 0

for i in range(n):
	ss = input()
	#print(ss)
	while('AB' in ss):
		ans += 1
		ss = ss.replace("AB", "", 1)
	if(ss[0] == "B" and ss[len(ss)-1] == "A"):
		both += 1
	elif(ss[0] == "B"):
		b_a += 1
	elif(ss[len(ss)-1] == "A"):
		a_a += 1

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

if(both >0 and a_a > 0 and b_a > 0):
	ans += 2
	both = 0
	a_a -= 1
	b_a -= 1
elif(both >0 and a_a > 0):
	both = 0
	a_a -= 1
	ans += 1
elif(both >0 and b_a > 0):
	both = 0
	b_a -= 1
	ans += 1

ans += min(a_a, b_a)

print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
eni_B = 0
end_A = 0
both = 0
count = 0

for i in range(N):
    s = list(input())
    if s[0] == 'B':
        eni_B += 1
    if s[-1] == 'A':
        end_A += 1
    if s[0] == 'B' and s[-1] == 'A':
        eni_B -= 1
        end_A -= 1
        both += 1
    for j in range(len(s)-1):
        if s[j] == 'A':
            if s[j+1] == 'B':
                count += 1


m = min(end_A,eni_B)
M = max(end_A,eni_B)

count = count + m

if M - m < both:
    count = count - m + M
    if both + m - M > 1:
        count =  count + both - 1
else:
    count = count + both

print(count)

Submission status: Wrong Answer

Solution code:
N=int(input())
s=' '
num_AB=0
num_A=0
num_B=0
for i in range(0,N):
    s=str(input())
    if(s[0]=='B'):
        num_B+=1
    if(s[-1]=='A'):
        num_A+=1
    for j in range(0,len(s)-1):
        if(s[j]=='A' and s[j+1]=='B'):
            num_AB+=1;
ext=min(num_A,num_B)
ext=min(ext,N-1)
ans=num_AB+min(num_A,num_B)
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = [input() for _ in range(N)]
ans = 0
ac = 0
bc = 0
abc = 0
for st in s:
    ans += st.count('AB')
    if st[-1] == 'A' and st[0] == 'B':
        abc += 1
    else:
        if st[-1] == 'A':
            ac += 1
        elif st[0] == 'B':
            bc += 1
absoluteNum = abs(ac - bc)
basicCon = min(ac, bc)
ans += basicCon + min(abc, absoluteNum)

if (absoluteNum < abc):
    ans += abc - 1
print(ans)

Submission status: Wrong Answer

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

cnt = 0
judge = 0
for i in range(n):
    for j in range(len(s[i])):
        if j != len(s[i]) - 1:
            if s[i][j] == "A":
                judge = 1
        if judge == 1 and s[i][j] != "A":
            if s[i][j] == "B":
                cnt += 1
                judge = 0
            else:
                judge = 0
        if j == len(s[i]) - 1:
            judge = 0
cnt_a = 0
cnt_b = 0
cnt_ab = 0
for i in range(n):
    len_s = len(s[i])
    if s[i][len_s - 1] == "A":
        cnt_a += 1
    if s[i][0] == "B":
        cnt_b += 1
    if s[i][0] == "B" and s[i][len_s - 1] == "A":
        cnt_ab += 1
if cnt_a == cnt_ab:
    print(cnt + min(cnt_a, cnt_b) - 1)
else:
    print(cnt + min(cnt_a, cnt_b))

Submission status: Wrong Answer

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:
        print(cnt + cnt_BA-1)
    elif cnt_A == 0 and cnt_B ==0 and cnt_BA ==0:
        print(cnt)
    else:
        print(cnt + min(cnt_BA+cnt_B, cnt_BA+cnt_A))
                
                
                
            
            
                

    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n=int(input())  #数値入力

list_s = []
for i in range(n):
    list_s.append(input())

sum_ab = 0
sum_ab += sum([x[:-1].count('AB') for x in list_s])

ba = 0
bx = 0
xa = 0
for x in list_s:
    if (x[0] == 'B') & (x[-1] == 'A'):
        ba += 1
    elif x[0] == 'B':
        bx += 1
    elif x[-1] == 'A':
        xa += 1
        
# print(ba, bx, xa)

if ba > 0:
    sum_ab += ba - 1

sum_ab += min(bx, xa)

if (ba > 0) & (bx != xa):
    sum_ab += 1

print(sum_ab)

Submission status: Wrong Answer

Solution code:
# coding: utf-8
# Your code here!

N = int(input())

count_AB = 0
count_last_A = 0
count_first_B = 0
count_both = 0
for i in range(N):
    s = input().rstrip()
    
    count_AB += len(s.split('AB')) - 1
    
    if s[0] == 'B' and s[-1] == 'A':
        count_both += 1
    elif s[0] == 'B':
        count_first_B += 1
    elif s[-1] == 'A' :
        count_last_A += 1

temp = 0
if count_both > 0:
    temp += count_both - 1
    count_last_A += 1
    count_first_B += 1

max_AB = max(count_last_A, count_first_B)
min_AB = min(count_last_A, count_first_B)
temp += min_AB

print(count_AB + temp)

Submission status: Wrong Answer

Solution code:
n,*s=open(0)
a=b=c=d=0
for t in s:
    if t[-2]=='A'and t[0]=='B':
        d+=1
    elif t[-2]=='A':
        a+=1
    elif t[0]=='B':
        b+=1
    c+=t.count('AB')
if all(i==0for i in(a,b)):
    print(c+d-1)
    exit()
ans=min(a,b)+c
dif=abs(a-b)
ans+=min(dif,d)
d-=min(dif,d)
print(ans+max(0,d-(a==b)))

Submission status: Wrong Answer

Solution code:
n = int(input())
x = 0
a = 0
b = 0
for _ in range(n):
    s = input()
    if s[0] == 'B':
        b += 1
    if s[-1] == 'A':
        a += 1
    for i in range(len(s)-1):
        if s[i:i+2] == 'AB':
            x += 1
print(x + min(a,b))

Submission status: Wrong Answer

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:
        if 'AB' in s:
            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: Wrong Answer

Solution code:
n = int(input())
words = [str(input()) for i in range(n)]
counter = 0
beginb = 0
enda = 0
mix = 0
for word in words:
    for index, letter in enumerate(word):
        if index<len(word)-1:
            if word[index] == 'A' and word[index+1] == 'B':
                counter += 1
    if word[0] == "B" and word[-1] == "A":
        mix += 1
    else:
        if word[0] == "B":
            beginb += 1
        if word[-1] == "A":
            enda += 1
diff = abs(beginb-enda)
print(counter,beginb,enda,diff,mix)

if diff > mix:
    print(counter+min(beginb,enda)+mix)
else:
    newmix = (mix-diff)//2
    print(counter+max(beginb,enda)+newmix)

Submission status: Wrong Answer

Solution code:
from sys import stdin
input=[]
input1=stdin.readline().rstrip()
N=int(input1[0])
for n in range(N):
  input.append(stdin.readline().rstrip())
#print(input)

output=0
count_A=0
count_B=0
for i in range(len(input)):
    if "AB" in input[i]:
        output+=1
    if "A" in input[i][len(input[i])-1]:
        count_A+=1
        #continue
    if "B" in input[i][0]:
        count_B+=1

if count_A<count_B:
    print(output+count_A)
else:
    print(output+count_B)

Submission status: Wrong Answer

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
# print(count)
if num_either >= 2:
	count += num_either-1
	num_either = 1
# print(num_A, num_B, num_either)
if num_A > num_B:
	if num_either == 1:
		count += num_B+1
	else:
		count += num_B
elif num_B > num_A:
	if num_either == 1:
		count += num_A+1
	else:
		count += num_A
else:
	if num_either == 1:
		count += num_A + 1
	else:
		count += num_A
print(count)

Submission status: Wrong Answer

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:
    print(d+c-1)
else:
    print(d+min(a+c,b+c))

Submission status: Wrong Answer

Solution code:
n = int(input())

count = 0
count_a = 0
count_b = 0
for i in range(n):
    s = input()
    if 'AB' in s:
        count += 1
    
    if s[0] == 'B':
        count_b += 1

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

#print('(count, A, B)=({}, {}, {})'.format(count, count_a, count_b))

ans = count + min(count_a, count_b)

print(ans)

Submission status: Wrong Answer

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 == num_start_with_B:
    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: Wrong Answer

Solution code:
N = int(input())
ans = 0
ls = []
rs = []
lr = []

for _ in range(N):
    s = str(input())
    if "AB" in s:
        ans += 1
    if s[-1] == "A" and s[0] == "B":
        lr.append(s)
    elif s[-1] == "A":
        rs.append(s)
    elif s[0] == "B":
        ls.append(s)
#print(ls)
#print(rs)
#print(lr)
if len(lr) > 0:
    anss = "AB"
else:
    anss = "C"
for _ in range(N - len(lr)):
    if len(rs) >= 1 and anss[0] == "B":
        anss = rs[0] + anss
        rs = rs[1::]
    elif len(ls) >= 1 and anss[-1] == "A":
        anss += ls[0]
        ls = ls[1::]
    elif len(ls) >= 1 and len(rs) >= 1:
        anss += rs[0]+ls[0]
        rs = rs[1::]
        ls = ls[1::]
    else:
        break
ans = anss.count("AB")
#print(anss,ans)
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = [input() for i in range(N)]
abc = sum([e.count("AB") for e in s]) # 各文字列のAB出現回数
bstart, aend = 0, 0
B_A = 0
for e in s:
    if e[0] == "B":
        bstart += 1
    if e[-1] == "A":
        aend += 1
    if e[0] == "B" and e[-1] == "A":
        B_A += 1
makedB_A = min(bstart-B_A, aend-B_A)
ans = 0

if bstart == aend:
    if makedB_A == 0:
        ans = abc + bstart - 1 
    else:
        ans = abc + bstart
else:
    ans = abc + min(bstart, aend)

    
print(ans)

Submission status: Wrong Answer

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 > cnt_a and cnt_ba > cnt_b:
            print(ans + cnt_ba)
      else:
            print(ans + min(cnt_a+cnt_ba, cnt_b+cnt_ba))
      
else:
      print(ans)