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:
#!/usr/bin/env python3
import collections as cl
import sys


def II():
    return int(sys.stdin.readline())


def MI():
    return map(int, sys.stdin.readline().split())


def LI():
    return list(map(int, sys.stdin.readline().split()))


def main():
    N = II()

    words = []
    starts_with_B = 0
    end_with_A = 0
    contain_AB = 0
    starts_with_B_and_end_with_A = 0
    for i in range(N):
        word = input()
        words.append(word)
        contain_AB += len(word) - len(word.replace("AB", "_"))

        if word[0] == "B" and word[-1] == "A":
            starts_with_B_and_end_with_A += 1
        elif word[0] == "B":
            starts_with_B += 1
        elif word[-1] == "A":
            end_with_A += 1

    if starts_with_B_and_end_with_A == 0:
        print(contain_AB + min(starts_with_B, end_with_A))
        return

    min_A_or_B = min(starts_with_B, end_with_A)
    amari = abs(starts_with_B - end_with_A)
    contain_AB += min_A_or_B

    available = amari // starts_with_B_and_end_with_A
    amari = amari % starts_with_B_and_end_with_A

    contain_AB += available * starts_with_B_and_end_with_A
    print(contain_AB + amari + starts_with_B_and_end_with_A - 1)


main()

Submission status: Wrong Answer

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


def II():
    return int(sys.stdin.readline())


def MI():
    return map(int, sys.stdin.readline().split())


def LI():
    return list(map(int, sys.stdin.readline().split()))


def main():
    N = II()

    words = []
    starts_with_B = 0
    end_with_A = 0
    contain_AB = 0
    for i in range(N):
        word = input()
        words.append(word)
        contain_AB += len(word) - len(word.replace("AB", "_"))
        if word[0] == "B":
            starts_with_B += 1
        if word[-1] == "A":
            end_with_A += 1

    print(contain_AB + min(starts_with_B, end_with_A))


main()

Submission status: Wrong Answer

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

s1,s2,s3,s4=[],[],[],[]
ans=0
for i in range(N):
  ans += s[i].count('AB')
  if s[i][0]=='B' and s[i][-1]=='A':
    s1.append(s[i])
  elif s[i][-1]=='A':
    s2.append(s[i])
  elif s[i][0]=='B':
    s3.append(s[i])
  else:
    s4.append(s[i])
    
if len(s2) and len(s3):
  ans += len(s1)+1
  ans += min(len(s2)-1,len(s3)-1)
  
elif len(s1) and len(s2):
  ans += len(s1)
  
elif len(s1) and len(s3):
  ans += len(s1)

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
ans = 0
s = []
ryotan = 0
atama = 0
oshiri = 0
for _ in range(n):
    _s = input()
    if _s[0] == "B" and _s[-1] == "A":
        ryotan += 1
    elif _s[0] == "B":
        atama += 1
    elif _s[-1] == "A":
        oshiri += 1
    A_flag = 0
    for c in _s:
        if c == "A" and A_flag == 0:
            A_flag = 1
        elif A_flag:
            if c == "B":
                ans += 1
                A_flag = 0
            else:
                A_flag = 0
if ryotan > 1:
    ans += ryotan - 1
if ryotan > 0:
    if atama > 0:
        ans += 1
        atama -= 1
    if oshiri > 0:
        ans += 1
        oshiri -= 1
ans += min(atama, oshiri)
print(ans)

Submission status: Wrong Answer

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

ans = 0
ea = 0
sb = 0
easb = 0

for s in S:
    ans += s.count("AB")
    if s[-1] == "A":
        ea += 1
    if s[0] == "B":
        sb += 1
    if s[-1] == "A" and s[0] == "B":
        easb += 1

ans += max(min(ea, sb), easb - 1)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys, math
from functools import lru_cache
import numpy as np
from collections import defaultdict
sys.setrecursionlimit(10**9)
MOD = 10**9+7

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return map(int, input().split())

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]


def main():
    N = ii()
    S = [input() for i in range(N)]

    k = sum(S[i].count('AB') for i in range(N))

    c = sum(1 for i in range(N) if S[i][-1] == 'A' and S[i][0] == 'B')
    a = sum(1 for i in range(N) if S[i][-1] == 'A') - c
    b = sum(1 for i in range(N) if S[i][0] == 'B') - c

    ans = k+c+min(a,b)
    if a == b == 0:
        ans -= 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

ans = 0
ea = 0
sb = 0

for s in S:
    ans += s.count("AB")
    if s[-1] == "A":
        ea += 1
    if s[0] == "B":
        sb += 1

ans += min(ea, sb)
print(ans)

Submission status: Wrong Answer

Solution code:
import sys, math
from functools import lru_cache
import numpy as np
from collections import defaultdict
sys.setrecursionlimit(10**9)
MOD = 10**9+7

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return map(int, input().split())

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]


def main():
    N = ii()
    S = [input() for i in range(N)]

    k = sum(S[i].count('AB') for i in range(N))

    c = sum(1 for i in range(N) if S[i][-1] == 'A' and S[i][0] == 'B')
    a = sum(1 for i in range(N) if S[i][-1] == 'A') - c
    b = sum(1 for i in range(N) if S[i][0] == 'B') - c

    print(k+c+min(a,b))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
import collections
c = 0
cc = collections.Counter()
for _ in range(int(raw_input())):
	w = raw_input()
	for u in range(len(w)-1):
		if w[u:u+2] == 'AB':
			c+=1
	w = w.replace('AB','')
	t = []
	for u in range(len(w)):
		if w[u] == 'A':
			if 'A' not in t:
				t.append('A')
		elif w[u] == 'B':
			if 'B' not in t:
				t.append('B')
	s = ''.join(t)
	if s: cc[s]+=1

r = []
while(True):
	if len(r) == 0 or r[-1] == 'B':
		if cc['A']:
			r.append('A')
			cc['A'] -= 1
		elif cc['BA']:
			r.append('A')
			cc['BA'] -= 1
		else:
			break
	else:
		if cc['BA']:
			c+=1
			r.append('A')
			cc['BA']-=1
		elif cc['B']:
			c+=1
			r.append('B')
			cc['B']-=1
		else:
			break

print c

Submission status: Wrong Answer

Solution code:
n = int(input())

_a = 0
b_ = 0
b_a = 0

cnt = 0

for i in range(n):
    s = input()

    sa = False
    sb = False
    if s[0] == "B":
        sb = True
    if s[-1] == "A":
        sa = True

    if sa and sb:
        b_a += 1
    elif sa:
        _a += 1
    elif sb:
        b_ += 1

    for j in range(len(s)-1):
        if s[j:j+2] == "AB":
            cnt += 1

if b_a > 0:
    cnt += b_a - 1
    if _a > 1:
        _a -= 1
        cnt += 1
    if b_ > 1:
        b_ -= 1
        cnt += 1

cnt += min(_a, b_)
print(cnt)

Submission status: Wrong Answer

Solution code:
n = int(input())

_a = 0
b_ = 0
b_a = 0

cnt = 0

for i in range(n):
    s = input()

    sa = False
    sb = False
    if s[0] == "B":
        sb = True
    if s[-1] == "A":
        sa = True

    if sa and sb:
        b_a += 1
    elif sa:
        _a += 1
    elif sb:
        b_ += 1

    for j in range(len(s)-1):
        if s[j:j+2] == "AB":
            cnt += 1

if b_a > 0:
    cnt += b_a - 1
    _a += 1
    b_ += 1

cnt += min(_a, b_)
print(cnt)

Submission status: Wrong Answer

Solution code:
import math
from itertools import combinations
from itertools import combinations_with_replacement
from itertools import product
from collections import defaultdict
from collections import deque
from collections import Counter
import heapq


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


def input_int():
    return int(input())


N = input_int()
b_head_cnt = 0
a_tail_cnt = 0
b_head_and_a_tail_cnt = 0   # 最初がBで最後がAの文字列を数え間違わないように
ans = 0
for _ in range(N):
    s = input()
    ans += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A':
        b_head_and_a_tail_cnt += 1
    elif s[0] == 'B':
        b_head_cnt += 1
    elif s[-1] == 'A':
        a_tail_cnt += 1
    else:
        # 何もしない
        pass

if abs(b_head_cnt - a_tail_cnt) >= b_head_and_a_tail_cnt:
    print(ans + min(b_head_cnt, a_tail_cnt) + b_head_and_a_tail_cnt)
else:
    print(ans + max(b_head_cnt, a_tail_cnt) + b_head_and_a_tail_cnt // 2)

Submission status: Wrong Answer

Solution code:
def main():
    n=int(input())
    s=[input() for _ in range(n)]
    count = 0
    b,e,r=0,0,0
    for ss in s:
        if "AB" in ss:
            count += 1
        if ss[0] == "B":
            if ss[-1] == "A":
                r += 1
            else:
                b += 1
        elif ss[-1] == "A":
            e += 1
    count += min(b,e)
    if b == 0 and e == 0:
        count += r-1
    else:
        count += r
    print(count)
            
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())
c1 = 0
c2 = 0
c3 = 0
ans = 0
for _ in range(N):
    s = input()
    for i in range(len(s) - 1):
        if s[i:i + 2] == 'AB':
            ans += 1
    if s[0] == 'B' and s[-1] == 'A':
        c3 += 1
    elif s[0] == 'B':
        c2 += 1
    elif s[-1] == 'A':
        c1 += 1


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

Submission status: Wrong Answer

Solution code:
N = int(input())
ans = 0
a_cnt = 0
b_cnt = 0
a_and_b_cnt = 0
for _ in range(N):
    s = input()
    for i in range(len(s) - 1):
        if s[i:i + 2] == 'AB':
            ans += 1
    if s[0] == 'B' and s[-1] == 'A':
        a_and_b_cnt += 1
    elif s[-1] == 'A':
        a_cnt += 1
    elif s[0] == 'B':
        b_cnt += 1
add = min(a_cnt, b_cnt)
diff = max(a_cnt, b_cnt) - min(a_cnt, b_cnt)
if diff:
    add += a_and_b_cnt
else:
    if a_and_b_cnt:
        add += a_and_b_cnt - 1
print(ans + add)

Submission status: Wrong Answer

Solution code:
N = int(input())
ans = 0
a_cnt = 0
b_cnt = 0
a_and_b_cnt = 0
for _ in range(N):
    s = input()
    for i in range(len(s) - 1):
        if s[i:i + 2] == 'AB':
            ans += 1
    if s[0] == 'B' and s[-1] == 'A':
        a_and_b_cnt += 1
    elif s[-1] == 'A':
        a_cnt += 1
    elif s[0] == 'B':
        b_cnt += 1
add = min(a_cnt, b_cnt)
diff = max(a_cnt, b_cnt) - min(a_cnt, b_cnt)
if diff:
    add += a_and_b_cnt
else:
    add += a_and_b_cnt - 1
print(ans + add)

Submission status: Wrong Answer

Solution code:
N = int(input())
ans = 0
a_cnt = 0
b_cnt = 0
a_and_b_cnt = 0
for _ in range(N):
    s = input()
    for i in range(len(s) - 1):
        if s[i:i + 2] == 'AB':
            ans += 1
    if s[0] == 'B' and s[-1] == 'A':
        a_and_b_cnt += 1
    elif s[-1] == 'A':
        a_cnt += 1
    elif s[0] == 'B':
        b_cnt += 1
for _ in range(a_and_b_cnt):
    if a_cnt < b_cnt:
        a_cnt += 1
    else:
        b_cnt += 1
print(ans + min(a_cnt, b_cnt))

Submission status: Wrong Answer

Solution code:
N = int(input())
ans = 0
a_cnt = 0
b_cnt = 0
for _ in range(N):
    s = input()
    for i in range(len(s) - 1):
        if s[i:i + 2] == 'AB':
            ans += 1
    if s[-1] == 'A':
        a_cnt += 1
    if s[0] == 'B':
        b_cnt += 1
print(ans + min(a_cnt, b_cnt))

Submission status: Wrong Answer

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

n = 0
Acount, Bcount,both = 0,0,0
for a in A:
    n += a.count("AB")
    if (a[0]=="B")&(a[-1]=="A"):both+=1
    elif a[0] == "B":Bcount+=1
    elif a[-1] == "A":Acount+=1

n += min(Acount,Bcount)
if Acount+Bcount>0:n += both
else:n += both-1
print(n)

Submission status: Wrong Answer

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

n = 0
Acount, Bcount,both = 0,0,0
for a in A:
    n += a.count("AB")
    if (a[0]=="B")&(a[-1]=="A"):
        both+=1
        continue
    if a[0] == "B":Bcount+=1
    if a[-1] == "A":Acount+=1

print(n+min(Acount,Bcount)+min(both,N-1))

Submission status: Wrong Answer

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

n = 0
Acount, Bcount,both = 0,0,0
for a in A:
    n += a.count("AB")
    if (a[0]=="B")&(a[-1]=="A"):
        both+=1
        continue
    if a[0] == "B":Bcount+=1
    if a[-1] == "A":Acount+=1

print(n+min(Acount,Bcount)+both)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
N = int(input())

cnt = 0
A = 0
B = 0
AB = 0

for _ in range(N):
  s = input()
  if s[0] == 'B':
    B += 1
  if s[-1] == 'A':
    A += 1
  if s[-1] == 'A' and s[0] == 'B':
    AB += 1
  for i in range(len(s)-1):
    if s[i] == 'A' and s[i+1] == 'B':
      cnt += 1
    
cnt += min(A,B)
if A == AB and B == AB:
  cnt -= 1
  
print(cnt)

Submission status: Wrong Answer

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
from collections import Counter
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

N = int(input())
ans = 0

end_a = 0
start_b = 0
both = 0
for i in range(N):
    S = input()
    ans += S.count("AB")
    if S[-1] == 'A' and S[0] == 'B':
        both += 1
    elif S[-1] == 'A':
        end_a += 1
    elif S[0] == 'B':
        start_b += 1

if both == 0:
    ans = min(start_b, end_a)
else:
    if start_b + end_a > 0:
        ans = both + min(start_b, end_a) + (1 if abs(start_b - end_a) > 0 else 0)
    else:
        ans = both - 1
# if end_a > start_b:
#     ans += start_b
#     end_a -= start_b
#     start_b = 0
# else:
#     ans += end_a
#     start_b -= end_a
#     end_a = 0

# if both >= 1:
#     ans += both - 1
#     if start_b > 0:
#         ans += 1
#     if end_a > 0:
#         ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
from collections import Counter
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

N = int(input())
ans = 0

end_a = 0
start_b = 0
both = 0
for i in range(N):
    S = input()
    ans += S.count("AB")
    if S[-1] == 'A' and S[0] == 'B':
        both += 1
    elif S[-1] == 'A':
        end_a += 1
    elif S[0] == 'B':
        start_b += 1
if end_a > start_b:
    ans += start_b
    end_a -= start_b
    start_b = 0
else:
    ans += end_a
    start_b -= end_a
    end_a = 0
if both >= 1:
    ans += both - 1
    if start_b > 0:
        ans += 1
    if end_a > 0:
        ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())

ans = 0
tail_a = 0
head_b = 0

for _ in range(N):
    s = input()
    ans += s.count('AB')
    tail_a += s[-1].count('A')
    head_b += s[0].count('B')

print(ans+min(tail_a, head_b))

Submission status: Wrong Answer

Solution code:
n = int(input())
last_a_cnt = 0
top_b_cnt = 0
last_a_top_b_cnt = 0
ab_cnt = 0

for _ in range(n):
    s = input()
    ab_cnt += s.count('AB')
    if s[0] == 'B' and s[-1] == 'A': last_a_top_b_cnt += 1
    elif s[0] == 'B' and s[-1] != 'A': top_b_cnt += 1
    elif s[0] != 'B' and s[-1] == 'A': last_a_cnt += 1


if last_a_cnt > 0:
    ans = 0
    last_a_cnt -= 1
    ans += last_a_top_b_cnt    
    ans += min(last_a_cnt+1, top_b_cnt)
    ans += ab_cnt

else:
    ans = 0
    ans += (last_a_top_b_cnt-1)
    ans += min(last_a_cnt+1, top_b_cnt)
    ans += ab_cnt

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import math
import copy
import heapq
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
sys.setrecursionlimit(1000000)

# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = float("inf")
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)

def nck(n, k, kaijyo):
    return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD

def npk(n, k, kaijyo):
    if k == 0 or k == n:
        return n % MOD
    return (kaijyo[n] * divide(kaijyo[n-k])) % MOD

def fact_and_inv(SIZE):
    inv = [0] * SIZE  # inv[j] = j^{-1} mod MOD
    fac = [0] * SIZE  # fac[j] = j! mod MOD
    finv = [0] * SIZE  # finv[j] = (j!)^{-1} mod MOD
    inv[1] = 1
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    for i in range(2, SIZE):
        inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD
        fac[i] = fac[i - 1] * i % MOD
        finv[i] = finv[i - 1] * inv[i] % MOD

    return fac, finv

def renritsu(A, Y):
    # example 2x + y = 3, x + 3y = 4
    # A = [[2,1], [1,3]])
    # Y = [[3],[4]] または [3,4]
    A = np.matrix(A)
    Y = np.matrix(Y)
    Y = np.reshape(Y, (-1, 1))
    X = np.linalg.solve(A, Y)

    # [1.0, 1.0]
    return X.flatten().tolist()[0]

class TwoDimGrid:
    # 2次元座標 -> 1次元
    def __init__(self, h, w, wall="#"):
        self.h = h
        self.w = w
        self.size = (h+2) * (w+2)
        self.wall = wall
        self.get_grid()
        # self.init_cost()

    def get_grid(self):
        grid = [self.wall * (self.w + 2)]
        for i in range(self.h):
            grid.append(self.wall + getS() + self.wall)

        grid.append(self.wall * (self.w + 2))
        self.grid = grid
    def init_cost(self):
        self.cost = [INF] * self.size

    def pos(self, x, y):
        # 壁も含めて0-indexed 元々の座標だけ考えると1-indexed
        return y * (self.w + 2) + x
    def getgrid(self, x, y):
        return self.grid[y][x]
    def get(self, x, y):
        return self.cost[self.pos(x, y)]
    def set(self, x, y, v):
        self.cost[self.pos(x, y)] = v
        return
    def show(self):
        for i in range(self.h+2):
            print(self.cost[(self.w + 2) * i:(self.w + 2) * (i+1)])
    def showsome(self, tgt):
        for t in tgt:
            print(t)
        return
    def showsomejoin(self, tgt):
        for t in tgt:
            print("".join(t))
        return

    def search(self):
        grid = self.grid
        move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        move_eight = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
        # for i in range(1, self.h+1):
        #     for j in range(1, self.w+1):
        #         cx, cy = j, i
        #         for dx, dy in move_eight:
        #             nx, ny = dx + cx, dy + cy


def soinsu(n):
    ret = defaultdict(int)
    for i in range(2, int(math.sqrt(n) + 2)):
        if n % i == 0:
            while True:
                if n % i == 0:
                    ret[i] += 1
                    n //= i
                else:
                    break

    if not ret:
        return {n: 1}
    return ret


def solve():
    n = getN()
    ans, a, b = 0,0,0
    andb = 0
    for i in range(n):
        prev = ""
        S = getS()
        for c in S:
            if prev == "A" and c == "B":
                ans += 1

            prev = c
        if S.startswith("B"):
            b += 1
        if S.endswith("A"):
            a += 1
        if S.startswith("B") + S.endswith("A"):
            andb = 0
            
    if a == b and b == andb and b > 0:
        b -= 1

    print(ans + min(a, b))



def main():
    n = getN()
    for _ in range(n):
        solve()

    return
if __name__ == "__main__":
    # main()
    solve()

Submission status: Wrong Answer

Solution code:
import sys
import math
import copy
import heapq
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
sys.setrecursionlimit(1000000)

# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = float("inf")
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)

def nck(n, k, kaijyo):
    return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD

def npk(n, k, kaijyo):
    if k == 0 or k == n:
        return n % MOD
    return (kaijyo[n] * divide(kaijyo[n-k])) % MOD

def fact_and_inv(SIZE):
    inv = [0] * SIZE  # inv[j] = j^{-1} mod MOD
    fac = [0] * SIZE  # fac[j] = j! mod MOD
    finv = [0] * SIZE  # finv[j] = (j!)^{-1} mod MOD
    inv[1] = 1
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    for i in range(2, SIZE):
        inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD
        fac[i] = fac[i - 1] * i % MOD
        finv[i] = finv[i - 1] * inv[i] % MOD

    return fac, finv

def renritsu(A, Y):
    # example 2x + y = 3, x + 3y = 4
    # A = [[2,1], [1,3]])
    # Y = [[3],[4]] または [3,4]
    A = np.matrix(A)
    Y = np.matrix(Y)
    Y = np.reshape(Y, (-1, 1))
    X = np.linalg.solve(A, Y)

    # [1.0, 1.0]
    return X.flatten().tolist()[0]

class TwoDimGrid:
    # 2次元座標 -> 1次元
    def __init__(self, h, w, wall="#"):
        self.h = h
        self.w = w
        self.size = (h+2) * (w+2)
        self.wall = wall
        self.get_grid()
        # self.init_cost()

    def get_grid(self):
        grid = [self.wall * (self.w + 2)]
        for i in range(self.h):
            grid.append(self.wall + getS() + self.wall)

        grid.append(self.wall * (self.w + 2))
        self.grid = grid
    def init_cost(self):
        self.cost = [INF] * self.size

    def pos(self, x, y):
        # 壁も含めて0-indexed 元々の座標だけ考えると1-indexed
        return y * (self.w + 2) + x
    def getgrid(self, x, y):
        return self.grid[y][x]
    def get(self, x, y):
        return self.cost[self.pos(x, y)]
    def set(self, x, y, v):
        self.cost[self.pos(x, y)] = v
        return
    def show(self):
        for i in range(self.h+2):
            print(self.cost[(self.w + 2) * i:(self.w + 2) * (i+1)])
    def showsome(self, tgt):
        for t in tgt:
            print(t)
        return
    def showsomejoin(self, tgt):
        for t in tgt:
            print("".join(t))
        return

    def search(self):
        grid = self.grid
        move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        move_eight = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
        # for i in range(1, self.h+1):
        #     for j in range(1, self.w+1):
        #         cx, cy = j, i
        #         for dx, dy in move_eight:
        #             nx, ny = dx + cx, dy + cy


def soinsu(n):
    ret = defaultdict(int)
    for i in range(2, int(math.sqrt(n) + 2)):
        if n % i == 0:
            while True:
                if n % i == 0:
                    ret[i] += 1
                    n //= i
                else:
                    break

    if not ret:
        return {n: 1}
    return ret


def solve():
    n = getN()
    ans, a, b = 0,0,0
    for i in range(n):
        prev = ""
        S = getS()
        for c in S:
            if prev == "A" and c == "B":
                ans += 1

            prev = c
        if S.startswith("B"):
            b += 1
        if S.endswith("A"):
            a += 1

    print(ans + min(a, b))



def main():
    n = getN()
    for _ in range(n):
        solve()

    return
if __name__ == "__main__":
    # main()
    solve()

Submission status: Wrong Answer

Solution code:
N=int(input())

answer=0
num_ba=0
num_a=0
num_b=0
for _ in range(N):
  s=input()
  for i in range(1,len(s)):
    if s[i-1]=="A" and s[i]=="B":
      answer+=1
  
  if s[0]=="B" and s[-1]=="A":
    num_ba+=1
  elif s[0]=="B":
    num_b+=1
  elif s[-1]=="A":
    num_a+=1

answer+=num_ba-1
if num_b>0:
  answer+=1
  num_b-=1
if num_a>0:
  answer+=1
  num_a-=1
  
answer+=min(num_a,num_b)
print(answer)

Submission status: Wrong Answer

Solution code:
n = int(input())
cnt_a = cnt_b = cnt_ba = 0
ans = 0
for _ in range(n):
    s = input()
    ans += s.count('AB')
    if s[0] == 'B':
        cnt_b += 1
        if s[-1] == 'A':
            cnt_ba += 1
    if s[-1] == 'A':
        cnt_a += 1

# print(ans, cnt_a, cnt_b)
if cnt_a == cnt_b == n:
    ans += n - 1
elif cnt_a == cnt_b == cnt_ba:
    ans += cnt_ba - 1
else:
    ans += min(cnt_a, cnt_b)
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
cnt_a = cnt_b = 0
ans = 0
for _ in range(n):
    s = input()
    ans += s.count('AB')
    if s[0] == 'B':
        cnt_b += 1
    if s[-1] == 'A':
        cnt_a += 1

# print(ans, cnt_a, cnt_b)
if cnt_a == cnt_b == n:
    ans += n - 1
else:
    ans += min(cnt_a, cnt_b)
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
cnt_a = cnt_b = 0
ans = 0
for _ in range(n):
    s = input()
    ans += s.count('AB')
    if s[0] == 'B':
        cnt_b += 1
    if s[-1] == 'A':
        cnt_a += 1

# print(ans, cnt_a, cnt_b)
ans += min(cnt_a, cnt_b)
print(ans)

Submission status: Wrong Answer

Solution code:
N=int(input())

#num_ab=0
balist=[]
blist=[]
alist=[]
others=[]
for _ in range(N):
  s=input()
  #for i in range(1,len(s)):
  #  if s[i-1]=="A" and s[i]=="B":
  #    num_ab+=1
  
  if s[0]=="B" and s[-1]=="A":
    balist.append(s)
  elif s[0]=="B":
    blist.append(s)
  elif s[-1]=="A":
    alist.append(s)
  else:
    others.append(s)
#print(balist,blist,alist,others)

answer_list=[]
while len(answer_list)<N:
  if not answer_list or answer_list[-1][-1]!="A":
    if alist:
      answer_list.append(alist.pop())
    elif balist:
      answer_list.append(balist.pop())
    elif blist:
      answer_list.append(blist.pop())
    else:
      answer_list.append(others.pop())
  else:
    if blist:
      answer_list.append(blist.pop())
    elif balist:
      answer_list.append(balist.pop())
    elif alist:
      answer_list.append(alist.pop())
    else:
      answer_list.append(others.pop())
      
answer_str="".join(answer_list)
#print(answer_str)

answer=0
for i in range(1,len(answer_str)):
  if answer_str[i-1]=="A" and answer_str[i]=="B":
    answer+=1
    
print(answer)

Submission status: Wrong Answer

Solution code:
N=int(input())

slist=[]
for _ in range(N):
  s=input()
  slist.append(s)
#print(slist)

AB_in_each=0
end_A=0
start_B=0

for s in slist:
  for i in range(1,len(s)):
    if s[i-1]=="A" and s[i]=="B":
      AB_in_each+=1
  if s[-1]=="A":
    end_A+=1
  if s[0]=="B":
    start_B+=1
    
#print(AB_in_each,end_A,start_B)
print(AB_in_each+min(end_A,start_B))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
n = int(input())
a = b = c = ans = 0
for _ in range(n):
    s = input()
    ans += s.count("AB")
    a += s[-1] == "A"
    b += s[0] == "B"
    c += s[-1] == "A" and s[0] == "B"
if a == c and b==c:
    print(ans + c -1)
else:
    print(ans + min(a, b))