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(raw_input())

inner_ab_count = 0
f_b_count = 0
l_a_count = 0

for n in xrange(N):
    s = raw_input()
    inner_ab_count += s.count('AB')
    if s[0] == 'B': f_b_count += 1
    if s[-1] == 'A': l_a_count += 1

result = inner_ab_count + min([l_a_count, f_b_count])
print result

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for i in range(n)]
count = 0
count_a = 0
count_b = 0
for i in range(n):
    count += s[i].count("AB")
    if s[i][-1] == "A":
        count_a += 1
    if s[i][0] == "B":
        count_b += 1
print(count+min([count_a,count_b]))

Submission status: Wrong Answer

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

x = ','.join(S).count('AB')

A = [ s[-1] == "A" for s in S ]
B = [ s[0] == "B" for s in S ]
y = min( A.count(True), B.count(True) )

print(x + y)

Submission status: Wrong Answer

Solution code:
N = int(input())
string_list = [input() for i in range(N)]
count = 0
A_count = 0
B_count = 0
for i in string_list:
    if 'AB' in i:
        count += 1
    if i[-1] == 'A':
        A_count += 1
    if i[0] == 'B':
        B_count += 1
count += min(A_count, B_count)
print(count)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
a = 0
b = 0
ins = 0
data = ""
for i in range(n):
    data = ""
    t = input()
    k = t.split("AB")
    for p in k:
        data += p
    #print(t[0], data[0], t[-1], data[-1], t)
    if data[0] == "B" and t[0] == data[0]:
        b+=1
    if data[-1] == "A" and t[-1] == data[-1]:
        a+=1
    ins += int((len(t)-len(data))/2)
    #print(ins)
print(min(a, b)+ins)

Submission status: Wrong Answer

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

cnt = 0
head_b_cnt = 0
end_a_CNT = 0
for word in s:
    cnt += word.count('AB')
    if word[0] == 'B':
        head_b_cnt += 1
    if word[-1] == 'A':
        end_a_CNT += 1

cnt += min(head_b_cnt, end_a_CNT)
print(cnt)

Submission status: Wrong Answer

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

start = 0
end = 0
c = 0
for x in s:
    if 'AB' in x:
        c += 1
    if x.startswith('B'):
        start += 1
    if x.endswith('A'):
        end += 1
if start > end:
    c += end
else:
    c += start
print(c)

Submission status: Wrong Answer

Solution code:
n = int(input())
ab_num = 0
a_num = 0
b_num = 0
double = 0
for _ in range(n):
    s = input()
    ab_num += s.count("AB")
    if s[0] == "B":
        b_num += 1
    if s[-1] == "A":
        a_num += 1
    if (s[0] == "B") & (s[-1] == "A"):
        double += 1
ans = ab_num + min(a_num, b_num)
if (a_num == double) & (b_num == double):
    ans = ab_num + double - 1    
print(ans)

Submission status: Wrong Answer

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

ans = sum(map(lambda x: x.count("AB"), ss))
x = y = z = 0
for s in ss:
    if s[0] == 'B' and s[-1] == 'A':
        y += 1
    elif s[-1] == 'A':
        x += 1
    elif s[0] == 'B':
        z += 1
ans += min(x,z) + y
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = [input() for _ in range(n)]
a = 0
b = 0
ab = 0
ans = 0
for i in range(n):
    ans += s[i].count('AB')
    if s[i][-1]=='A' and s[i][0]=='B':
        ab += 1
        continue
    if s[i][-1]=='A':
        a += 1
    if s[i][0]=='B':
        b += 1
if a>=b:
    k = min(ab,a-b)
    ans += b+k+(ab-k)//2+(ab-k)%2
    if a>0 or b>0:
        ans += 1
else:
    k = min(ab,b-a)
    ans += a+k+(ab-k)//2+(ab-k)%2
    if a>0 or b>0:
        ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [input() for _ in range(N)]
start_B = sum([1 if s[0]=='B' else 0 for s in S])
end_A = sum([1 if s[-1]=='A' else 0 for s in S])
AB = sum([s.count('AB') for s in S])

print(AB+min(start_B, end_A))

Submission status: Wrong Answer

Solution code:
import re

N = int(input())
lst = []

for i in range(N):
    s = input()
    n = len(re.findall(r'AB', s))
    m = len(re.findall(r'A$', s))
    l = len(re.findall(r'^B', s))
    lst.append((n, m, l))


ans = sum([l[0] for l in lst]) + min(sum([l[1] for l in lst]),sum(l[2] for l in lst))

print(ans)

Submission status: Wrong Answer

Solution code:

# coding: utf-8

# In[7]:

import sys
input = sys.stdin.readline
N = int(input())
S = [input() for i in range(N)]


# In[9]:

b_cnt = 0
a_cnt = 0
for i in range(N):
    if S[i][0]=='B':
        b_cnt += 1
    if S[i][-1]=='A':
        a_cnt += 1
#print(b_cnt, a_cnt)
print('/'.join(S).count('AB') + min(a_cnt, b_cnt))


# In[ ]:

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
for i in s:
    cnt += i.count('AB')
    if i[0] == 'B':
        sentou_b += 1
    if i[-1] == 'A':
        ushiro_a += 1

print(cnt+min(sentou_b, ushiro_a))

Submission status: Wrong Answer

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

a_list = []
both = []
b_list = []
remain = []

for i, s in enumerate(s_list):
    if s[0] == "B" and s[-1] == "A":
        both.append(s)

    elif s[-1] == "A":
        a_list.append(s)

    elif s[0] == "B":
        b_list.append(s)

    else:
        remain.append(s)
ans = 0
last = ""
while True:
    if len(a_list) != 0:
        if len(b_list) != 0:
            a = a_list.pop()
            b = b_list.pop()
        elif len(both) != 0:
            a = a_list.pop()
            b = both.pop()
        else:
            break
    elif len(both) != 0:
        if len(b_list) != 0:
            a = both.pop()
            b = b_list.pop()
        elif len(both) >= 2:
            a = both.pop()
            b = both.pop()
        else:
            break
    else:
        break
    ans += 1
    ans += a.count("AB")
    ans += b.count("AB")
    last = b[-1]

if last == "A" and (len(b_list) != 0 or len(both) != 0):
    if len(b_list) != 0:
        ans += 1
        b = b_list.pop()
        ans += b.count("AB")
    else:
        b = both.pop()
        ans += 1
        ans += b.count("AB")

while len(a_list) != 0:
    a = a_list.pop()
    ans += a.count("AB")


while len(b_list) != 0:
    a = b_list.pop()
    ans += a.count("AB")

while len(both) != 0:
    a = both.pop()
    ans += a.count("AB")

while len(remain) != 0:
    a = remain.pop()
    ans += a.count("AB")

print(ans)

Submission status: Wrong Answer

Solution code:
#d=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
#import numpy as np
#n=int(input())
#li=input().split()
#import fractions
#lis=list(map(int,input().split()))

n=int(input())
S=[]
ans=0
firstB,lastA,bothAB=0,0,0

for i in range(n):
    S.append(input())
    flag=0
    for j in range(len(S[-1])-1):
        if S[-1][j:j+2]=="AB":
            ans+=1
    if S[-1][0]=="B":
        firstB+=1
        flag+=1
    if S[-1][-1]=="A":
        lastA+=1
        flag+=1
    if flag==2:
        bothAB+=1
        firstB-=1
        lastA-=1

ans+=min(firstB,lastA)+bothAB

print(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')
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)
if dif>d and a>b:
    print(ans+1)
else:
    d-=dif
    print(ans+d)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())

b = 0
a = 0
count = 0
for i in range(N):
    s = input()
    count += sum([1 for j in range(len(s)) if s[j:j + 2] == "AB"])
    if s[-1] == "A":
        a += 1
    if s[0] == "B":
        b += 1

print(count + min([a, b]))

Submission status: Wrong Answer

Solution code:
N = int(input())

AB_cnt = 0
A_cnt = 0
B_cnt =0
for i in range(N):
    S = input()
    AB_cnt += S.count('AB')
    if S[-1] == 'A':
        A_cnt += 1
    if S[0] == 'B':
        B_cnt += 1

print(AB_cnt + min(A_cnt, B_cnt))

Submission status: Wrong Answer

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

N = int(input())
s = []
cnt = 0
a = 0
b = 0
ab = 0
for i in range(N):
    s.append(input())
for str in s:
    if "AB" in str:
        cnt = cnt + 1
    if str[-1:] == "A":
        a = a + 1
    if str[0:1] == "B":
        b = b + 1
    if str[-1:] == "A" and str[1:] == "B":
        ab = ab + 1

print(cnt+min(a, b)-ab)

Submission status: Wrong Answer

Solution code:
# coding:utf-8

import sys
from collections import deque, Counter

INF = float('inf')
MOD = 10 ** 9 + 7
dy, dx = (0, -1, 0, 1), (1, 0, -1, 0)

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()


def main():
    n = II()
    S = [SI() for _ in range(n)]

    cnt = {"B_": 0, "_A": 0, "B_A": 0}
    res = 0
    for s in S:
        for i in range(len(s) - 1):
            if s[i: i + 2] == 'AB':
                res += 1

        if s[0] == 'B' and s[-1] == 'A':
            cnt["B_A"] += 1
        elif s[0] == 'B':
            cnt["B_"] += 1
        elif s[-1] == 'A':
            cnt["_A"] += 1

    # print(res, cnt)
    res += min(cnt["B_"], cnt["_A"])
    if abs(cnt["B_"] - cnt["_A"]):
        res += cnt["B_A"]
    else:
        res += max(0, cnt["B_A"] - 1)

    print(res)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())
cnt = 0
na = 0
nb = 0
for i in range(N):
    s = input()
    cnt += s.count('AB')
    if s[-1] == 'A':
        na += 1
    if s[0] == 'B':
        nb += 1
print(cnt+min(na,nb))

Submission status: Wrong Answer

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

ea=0
sb=0
cnt= 0
for s in ss:
    cnt+= s.count("AB")
    if s[-1]=="A": ea+=1
    if s[ 0]=="B": sb+=1
#
print( cnt + min(ea,sb) )

Submission status: Wrong Answer

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

ab_count = 0
b_start = 0
a_end = 0
concat_max = 0

for s in s_list:
    is_b = s[0] == 'B'
    is_a = s[-1] == 'A'
    if is_b:
        b_start = b_start + 1
    if is_a:
        a_end = a_end + 1
    if is_a or is_b:
        concat_max = concat_max + 1
    ab_count = ab_count + s.count('AB')

print(ab_count + min(min(a_end, b_start), concat_max - 1))

Submission status: Wrong Answer

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

ans = cnt_a = cnt_b = 0
for s in S:
    ans += s.count("AB")
    if s[-1] == "A":
        cnt_a += 1
    if s[0] == "B":
        cnt_b += 1
ans += min(cnt_a, cnt_b, N - 1)

print(ans)

Submission status: Wrong Answer

Solution code:
N=input()
LL=[]
def find(s):
    count=0
    for i in xrange(len(s)-1):
        if s[i]+s[i+1]=='AB':
            count+=1
    return count        

ans=0
start_B=0
end_A=0
same_time=0
for i in xrange(N):
    s=raw_input()
    ans+=find(s)
    if s[-1]=='A':
        end_A+=1
    if s[0]=='B':
        start_B+=1   
    if s[0]=='B' and s[-1]=='A':
        same_time+=1



if end_A!=start_B:
    print(ans+min(end_A,start_B)-same_time+1+(same_time-1))
else:
    print(ans+min(end_A,start_B)-same_time+max(0,(same_time)-1))

Submission status: Wrong Answer

Solution code:
N = int(input())

ans = 0
ra = 0
lb = 0
ba = 0
not_ra_nor_lb = 0

for _ in range(N):
    s = input()
    ans += s.count("AB")
    if s[0] == "B":
        lb += 1
    if s[-1] == "A":
        ra += 1
    if (s[0] == "B") & (s[-1] == "A"):
        ba += 1
    if (s[0] != "B") & (s[-1] != "A"):
        not_ra_nor_lb += 1

if ba + not_ra_nor_lb == N:
    ans += ra - 1
else:
    ans += min(ra, lb)

print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
a_count =0
b_count =0
ab_count =0
for i in range(N):
    test = str(input())
    if test[0] == "B":
        b_count +=1
    if test[-1] == "A":
        a_count += 1
    ab_count += test.count("AB")
if a_count == N:
    if b_count == N:
        a_count += -1
print(ab_count+min(a_count,b_count))

Submission status: Wrong Answer

Solution code:
N = int(input())
B_start_cnt = 0
A_end_cnt = 0
AB_cnt = 0
for i in range(N):
    s = input()
    if s[0] == "B":
        B_start_cnt += 1
    if s[-1] == "A":
        A_end_cnt += 1
    AB_cnt += s.count('AB')
ans = min(A_end_cnt,B_start_cnt)+AB_cnt
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
count=0
bx=0
xa=0
ba=0
for i in range(n):
    s=input()
    for j in range(0,len(s)-1):
        if s[j:j+2]=='AB':
            count=count+1
    if s[0]=='B' and s[len(s)-1]=='A':
        ba=ba+1
    if s[0]=='B' and not s[len(s)-1]=='A':
        bx=bx+1
    if not s[0]=='B' and s[len(s)-1]=='A':
        xa=xa+1
if bx*xa==0:
    if ba>=2:
        count=count+ba-1
else:
    count=count+ba+min(xa,bx)
print(count)

Submission status: Wrong Answer

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

top = [0 for _ in range(N)]
last = [0 for _ in range(N)]

res = 0
n = 0
for s in S:
    for i in range(len(s)-1):
        if s[i] == 'A' and s[i+1] == 'B':
            res += 1
            
    if s[0] == 'B':
        top[n] = 1
        
    if s[-1] == 'A':
        last[n] = 1
        
    n += 1
 
d = 0
t = 0
l = 0
for i in range(N):
    if top[i] == 1 and last[i] == 1:
        d += 1
    elif top[i] == 1:
        t += 1
    elif last[i] == 1:
        l += 1
        
res += min(t, l)

res += min(d, max(t, l) - min(t, l))
d -= min(d, max(t, l) - min(t, l))
d += 1

if d > 0:
    res += d//2
    
print(res)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

a = 0
b = 0
ab = 0
ba = 0
for i in s:
  if i[0] == "B":
    b += 1
  if i[-1] == "A":
    a += 1
  if i[0] == "B" and i[-1] == "A":
    ba += 1
  ab += i.count("AB")
  
if ba == b:
  aa = a - 1
else:
  aa = a
if ba == a:
  bb = b - 1
else:
  bb = b

print(min(aa, bb) + ab)

Submission status: Wrong Answer

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

counter = 0
begin_b = []
end_a = []
for i in range(n):
    counter += s[i].count('AB')
    if s[i][0] == 'B':
        begin_b.append(i)
    if s[i][-1] == 'A':
        end_a.append(i)

if len(begin_b) == n and len(end_a) == n:
    print(counter + min(len(begin_b), len(end_a)) - 1)
else:
    print(counter + min(len(begin_b), len(end_a)))

Submission status: Wrong Answer

Solution code:
N =int(input())
co = {0:0,1:0,2:0,3:0}
ans = 0
foo =0
for _ in range(N):
    i = input()
    foo = 0
    if i[0] =="B":
        foo += 1
    if i[-1] =="A":
        foo += 2
    co[foo] += 1
    ans += i.count("AB")
ans +=  min(co[1],co[2])
if min(co[1],co[2])==0:
    ans += co[3]
    if co[1]==0 and co[2] == 0:
        ans -= 1 
print(ans)

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

    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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:
    ans += BA[1][1]-1
else:
    ans += min(BA[1][0],BA[0][1]) + BA[1][1]

print(ans)

Submission status: Wrong Answer

Solution code:
import sys, math, collections, heapq, itertools
F = sys.stdin
def single_input(): return F.readline().strip("\n")
def line_input(): return F.readline().strip("\n").split()
def gcd(a, b):
    a, b = max(a, b), min(a, b)
    while a % b > 0:
        a, b = b, a % b
    return b
  
def solve():
    N = int(single_input())
    ab = 0
    startB, endA, both = set(), set(), set()
    for i in range(N):
        s = str(single_input())
        for j in range(len(s) - 1):
            if s[j:j+2] == "AB": ab += 1
        if s[0] == "B" and s[-1] == "A": both |= {i}
        elif s[0] == "B": startB |= {i}
        elif s[-1] == "A": endA |= {i}

        
    ab += max(len(both) - 1, 0)
    single = min(len(startB), len(endA))
    if both: single += 1
    ab += single
    print(ab)
    
    return 0
  
if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
N=int(input())
btoa=0
enda=0
startb=0
ab=0
for i in range(N):
	buf=input()
	if buf[0]=="B" and buf[-1]=="A":
		btoa+=1
	elif buf[-1]=="A":
		enda+=1
	elif buf[0]=="B":
		startb+=1
	ab+=buf.count("AB")
if btoa>=1:
	res=ab+btoa-1
else:
	res=ab
if enda!=0 or startb!=0:
	enda+=1
	startb+=1
	print(res+min(enda,startb))
else:
	print(res)

Submission status: Wrong Answer

Solution code:
N = int(input())
s = list(input()for i in range(N))
ans = 0
A,B = 0,0
AB = 0
for i in s:
    for j in range(len(i)-1):
        if i[j:j+2] == "AB":
            ans += 1
    if i[0] == "B":
        B += 1
    if i[-1] == "A":
        A += 1
    if i[0] == "B" and i[-1] == "A":
        AB += 1
ans += min(A,B)
if A==B and B == AB:
    ans -= 1
print(ans)

Submission status: Wrong Answer

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

k = sum(t.count('AB') for t in s)
ab = sum(t[-1] == 'A' and t[0] == 'B' for t in s)
a = sum(t[-1] == 'A' and t[0] != 'B' for t in s)
b = sum(t[-1] != 'A' and t[0] == 'B' for t in s)
d = abs(a - b)
d2 = max(0, ab - d)
ans = k
f = a > 0 or ab > 0
if a > 0 and ab > 0:
    ans += 1
    ab -= 1
    a -= 1
elif a == 0:
    ab -= 1
ans += ab
if f and b > 0:
    ans += 1
    b -= 1
ans += min(a, b)
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())

str_list = []
AB_count = 0
A_end = 0
B_start = 0
for i in range(N):
    string = input()
    AB_count += string.count("AB")
    
    if string[0] == "B":
        B_start += 1
    if string[-1] == "A":
        A_end += 1

new_AB = min(A_end,B_start)

print(AB_count+new_AB)

Submission status: Wrong Answer

Solution code:
words = lambda t : list(map(t, input().split()))
n = int(input())

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

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

Submission status: Wrong Answer

Solution code:
N = int(input())
ss = [input() for _ in range(N)]
cnt = 0
ba = 0
b = 0
a = 0
o = 0
import re
for s in ss:
    cnt += len(re.findall('AB', s))
    if s[-1] == 'A' and s[0] == 'B':
        ba += 1
    elif s[-1] == 'A':
        a += 1
    elif s[0] == 'B':
        b += 1
    else:
        o += 1

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

print(cnt)

Submission status: Wrong Answer

Solution code:
n = int(input())
ans = 0
last_a = 0
first_b = 0
for i in range(n):
  s = input()
  ans += s.count('AB')
  if s[0] == 'B':
    first_b+=1
  if s[-1] == 'A':
    last_a+=1
print(ans+min(last_a,first_b))

Submission status: Wrong Answer

Solution code:
n=int(input())
fir=0
sec=0
same=0
ret = 0
for i in range(n):
    s = input()
    if 'AB' in s:
        ret+=1
    if s[0]=='B':
        fir+=1
    if s[-1]=='A':
        sec+=1
    if s[0]=='B' and s[-1]=='A':
        same+=1
ret+=same
if same>0:
    fir-=same-1
if same>0:
    sec-=same-1
if same>0:
    ret-=1
print(ret+min(fir,sec))

Submission status: Wrong Answer

Solution code:

N=int(input())

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


while True:
    if(ab<=0):
        break
    if(a>0 and b>0):
        ans+=2
        a-=1
        b-=1
        ab-=1
    elif(a>0):
        ans+=1
        a-=1
        ab-=1
        if(ab>=0):
            ans+=1
            ab-=1
    elif(b>0):
        ans+=1
        b-=1
        ab-=1
        if(ab>=0):
            ans+=1
            ab-=1
    

ans+=max(min([a,b]),0)
print(ans)

Submission status: Wrong Answer

Solution code:
# coding:utf-8

import math
import re

def main(params):
    total = 0
    a = []
    b = []
    for i in range(len(params)):
        s = params[i]
        total += s.count("AB")
        if s[0] == "B":
            b.append(i)
        if s[-1:] == "A":
            a.append(i)
    if len(a) == len(b):
        total += min(len(a), len(b))
        for i in a:
            chk = True
            if not i in b:
                chk = False
            if chk == True:
                total -= 1

    else:
        total += min(len(a),len(b))
    print total

if __name__ == "__main__":
    n = int(raw_input())
    #cnt = 1 # TODO: edit here
    params = []
    for i in range(n):
        param = raw_input()
        params.append(param)
    main(params)

Submission status: Wrong Answer

Solution code:
N = int(input())
S = [None] * N

count_AB = 0
right_A = 0
left_B = 0
right_A_left_B = 0

for i in range(N):
    s = input()
    count_AB += s.count('AB')
    if s[0] == "B" and s[-1] == "A":
        right_A_left_B += 1
    elif s[0] == "B":
        left_B += 1
    elif s[-1] == "A":
        right_A += 1

if right_A_left_B > 0:
    count_AB += (right_A_left_B - 1)
    right_A_left_B = 1

min_AB = min(right_A, left_B)
count_AB += min_AB

# which one is 0
right_A = abs(right_A - min_AB)
left_B = abs(left_B - min_AB)

if right_A_left_B > 0 and (right_A + left_B) > 0:
    count_AB += 1
    right_A_left_B = 0
    if right_A > 0:
        right_A -= 1
        left_B += 1
    else:
        left_B -= 1
        right_A += 1
if left_B > 0 and right_A:
    count_AB += 1

print(count_AB)

Submission status: Wrong Answer

Solution code:
n = int(input())
s = []
ca = 0
cb = 0
for i in range(n):
    tmp = input()
    s.append(tmp)
    if tmp[-1] == "A":
        ca += 1
    if tmp[0] == "B":
        cb += 1
cnt = 0
for i in range(n):
    cnt += s[i].count("AB")
if min(ca, cb) >= n - 1:
    cnt -= 1
print(cnt + min(ca, cb))

Submission status: Wrong Answer

Solution code:
n=int(input())
s=[input() for i in range(n)]
cnt1=0
cnt2=0
cnt3=0
cnt4=0
for si in s:
    if si[0]=='B' and si[-1]=='A':
        cnt1+=1
    elif si[0]=='B':
        cnt2+=1
    elif si[-1]=='A':
        cnt3+=1
    for i in range(len(si)-1):
        if si[i]=='A' and si[i+1]=='B':
            cnt4+=1
if cnt2>=1:
    if cnt3>=1:
        print(cnt4+cnt1+min(cnt2, cnt3))
    else:
        print(cnt4+cnt1)
else:
    if cnt3>=1:
        print(cnt4+cnt1)
    else:
        print(cnt4-1+cnt1)

Submission status: Wrong Answer

Solution code:
import re
n = int(input())
lst = []
ab = 0
a = 0
b = 0
for i in range(n):
  x = input()
  lst.append(x)
  if "AB" in x:
    ab += len(re.findall('AB', x))
  if x[0] == "B":
    a += 1
  if x[-1] == "A":
    b += 1
print(ab+min(a,b))

Submission status: Wrong Answer

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

ans = 0
start_B = 0
end_A = 0
B_A = 0
for s in s_list:
  ans += s.count("AB")
  if s[0] == "B":
    start_B += 1
  if s[-1] == "A":
    end_A += 1
  if s[0] == "B" and s[-1] == "A":
    B_A += 1

ans += min(start_B, end_A)
if B_A == max(start_B, end_A):
  ans -= 1
print(ans)

Submission status: Wrong Answer

Solution code:
from sys import stdin
# import numpy as np
# import math
# import fractions
# import sys
# sys.setrecursionlimit(100000)
# N = int(stdin.readline().rstrip().split()[0])
# A = [int(x) for x in stdin.readline().rstrip().split()]
# N, X = [int(x) for x in stdin.readline().rstrip().split()]
# S = stdin.readline().rstrip().split()[0]

N = int(stdin.readline().rstrip().split()[0])

_A = 0
AB = 0
B_ = 0
B_A = 0
for _ in range(N):
  s = stdin.readline().rstrip().split()[0]
  AB += s.count("AB")
  a=0
  b=0
  if s[0] == "B":
    b = 1
  if s[-1] == "A":
    a = 1
  if a == 1 and b == 1:
    B_A += 1
  _A += a
  B_ += b

if _A == B_ == B_A:
  print(AB)
else:
  _AB_ = min(_A, B_)
  print(AB+_AB_)

Submission status: Wrong Answer

Solution code:
import numpy as np

n=int(input())
a=0
b=0
ab=0
count=0
for i in range(n):
    s=input()
    if s[0]=='B':
        a+=1
    if s[-1]=='A':
        b+=1
    if s[0]=='B' and s[-1]=='A':
        ab+=1
    for j in range(len(s)-1):
        if s[j]=='A' and s[j+1]=='B':
            count+=1
if a==b and ab>1:
    count+=min([a,b])-1
else:
    count+=min([a,b])
print(count)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())
s = [input() for i in range(N)]
l1 = [s[i].count('AB') for i in range(N)]
l2 = [1 if s[i][0] == 'B' else 0 for i in range(N)]
l3 = [1 if s[i][-1] == 'A' else 0 for i in range(N)]
l4 = [l2[i]*l3[i] for i in range(N)]
print(sum(l1) + min(sum(l2),sum(l3)))