Problem:


Score : 600 points

Problem Statement

You are given a string s consisting of A, B and C.

Snuke wants to perform the following operation on s as many times as possible:

Choose a contiguous substring of s that reads ABC and replace it with BCA.

Find the maximum possible number of operations.

Constraints

1 \leq |s| \leq 200000

Each character of s is A, B and C.

Input

Input is given from Standard Input in the following format:

s

Output

Find the maximum possible number of operations.

Sample Input 1

ABCABC

Sample Output 1

3

You can perform the operations three times as follows: ABCABC → BCAABC → BCABCA → BCBCAA. This is the maximum result.

Sample Input 2

C

Sample Output 2

0

Sample Input 3

ABCACCBABCBCAABCB

Sample Output 3

6



Sample input:
ABCABC


Sample output:
3

Submission status: Accepted

Solution code:
S = input() + "$"
L = len(S)
SS = []
E = []
i = 0
while i < L:
    if S[i] == 'A':
        E.append(0)
        i += 1
        continue
    if S[i:i+2] == 'BC':
        E.append(1)
        i += 2
        continue
    if E:
        SS.append(E)
        E = []
    i += 1

ans = 0
for E in SS:
    cur = 0
    for c in reversed(E):
        if c:
            cur += 1
        else:
            ans += cur
print(ans)

Submission status: Accepted

Solution code:
from functools import reduce

# 入力
s = input()

# AA..ABC -> BCAA..A に変換するのを繰り返す
ans, _, _ = reduce(
    lambda acc, c:
        (acc[0], (1 - acc[2]) * acc[1] + 1, 0) if c == 'A' else
        (acc[0], (1 - acc[2]) * acc[1], 1 - acc[2]) if c == 'B' else
        (acc[0] + acc[2] * acc[1], acc[2] * acc[1], 0),
    s,
    (0, 0, 0)
)

# 出力
print(ans)

Submission status: Accepted

Solution code:
#import numpy as np
#from numpy import*
#from scipy.sparse.csgraph import shortest_path #shortest_path(csgraph=graph) # dijkstra# floyd_warshall
#from scipy.sparse import csr_matrix
 
from collections import* #defaultdict Counter deque appendleft
from fractions import gcd
from functools import* #reduce
from itertools import* #permutations("AB",repeat=2) combinations("AB",2) product("AB",2) groupby accumulate
from operator import mul,itemgetter
from bisect import* #bisect_left bisect_right
from heapq import* #heapify heappop heappushpop
from math import factorial,pi
from copy import deepcopy
import sys
sys.setrecursionlimit(10**8)
#input=sys.stdin.readline  #危険！基本オフにしろ！
 
def main():
    s=input().replace("BC","X")
#    print(s)
    c=0
    d=0
    for i in s:
        if i=="A":
            c+=1
        elif i=="X":
            d+=c
        else:
            c=0
    print(d)
#    while "AX" in s:
#        s=s.replace("AX","XA")
#        print(s)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s = input()
ans = 0
cntA = 0
for i in range(0, len(s) - 1):
    if s[i] == 'A':
        cntA += 1
    elif s[i: i + 2] == "BC":
        ans += cntA
    elif i > 0 and s[i - 1: i + 1] == "BC":
        continue
    else:
        cntA = 0
print(ans)

Submission status: Accepted

Solution code:
s = input() + "_"

a = 0
r = 0
i = 0

while i < len(s):
    if s[i] == "A":
        a += 1
        i += 1
    elif s[i] == "B":
        if s[i + 1] == "C":
            r += a
            i += 2
        else:
            a = 0
            i += 1
    else:
        a = 0
        i += 1

print(r)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 13 09:53:12 2019
 
@author: Owner
"""
import collections
 
#素因数を並べる
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
 
class UnionFind(object):
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]
 
    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]
 
    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]
 
    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)
 
    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]
    
 
"""
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]
 
#Distance Transformation
    for h in range(0,H):
        for w in range(0,W):
            if h == 0 and w == 0:
                pass
            elif h == 0:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h-1][W-w]+1)
            elif w == 0:   
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1)
            else:
                D[H-h-1][W-w-1]= min(D[H-h-1][W-w-1], D[H-h][W-w-1]+1, D[H-h-1][W-w]+1, D[H-h][W-w]+2)
            d_max = max(D[H-h-1][W-w-1], d_max)
 
"""
 
 
 
s = input()
S = collections.deque(s)
def main():     
    res = 0
    
    past = ""
    now = ""
    cnt_bc = 0
    flg_bc = False
    for n,s in enumerate(reversed(S)):
        if s == "A" and flg_bc:
            res += cnt_bc
            continue
        now = s 
        if past == "C" and now == "B":
            cnt_bc += 1
            flg_bc = True
        elif past == "C" and now == "C":
            cnt_bc = 0
            flg_bc = False
        elif past == "B" and now == "B":
            cnt_bc = 0
            flg_bc = False
        elif past == "B" and now == "C":
            flg_bc = False
        else:
            cnt_bc = 0
            flg_bc = False
        past = now
        
    
    print(res)
                
                
                
            
            
                
 
    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    S = input()
    N = len(S)
    A = 0
    ans = 0
    i = 0
    while i < N:
        if S[i] == "A":
            A += 1
            i += 1
        elif i+1 < N and S[i] == "B" and S[i+1] == "C":
            ans += A
            i += 2
        else:
            A = 0
            i += 1
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
cnt, tmp = 0, 0
for c in input().replace("BC", "X"):
  if c == "A":
    tmp += 1
  elif c == "X":
    cnt += tmp
  else:
    tmp = 0
print(cnt)

Submission status: Accepted

Solution code:
s = "Z".join(input().split("BC"))
l = len(s)
count = 0
cue = 0
for i in range(l):
	if s[i] == "A":
		cue += 1
	elif s[i] == "Z":
		count += cue
	else:
		cue = 0
print(count)

Submission status: Accepted

Solution code:
s = input()

inversion = 0
count_a = 0
for si in s.replace("BC", "D"):
    if si == "A":
        count_a += 1
    elif si == "D":
        inversion += count_a
    else:
        count_a = 0

print(inversion)

Submission status: Accepted

Solution code:
s = input().strip()
len_s = len(s)
i = a = bc = ans = 0
while i < len_s:
    if s[i] == 'A':
        a += 1
        i += 1
    elif s[i:i+2] == 'BC':
        bc = 1
        ans = ans + bc * a
        i += 2
    else:
        a = bc = 0
        i += 1

print(ans)

Submission status: Accepted

Solution code:
# for i, a in enumerate(iterable)
# q, mod = divmod(a, b)
# divmod(x, y) returns the tuple (x//y, x%y)
# manage median(s) using two heapq https://atcoder.jp/contests/abc127/tasks/abc127_f
# visual studio code shortcut https://qiita.com/TakahiRoyte/items/cdab6fca64da386a690b
# delete line: Ctrl+Shift+k
# choose same words: Ctrl+Shift+l
import sys
from itertools import combinations, permutations # https://docs.python.org/ja/3/library/itertools.html
from math import factorial
def combinations_count(n, r):
    # faster than the following code
    # def combinations_count(n, r):
    #     return factorial(n) // (factorial(n - r) * factorial(r))
    if n - r < r: r = n - r
    if r == 0: return 1
    if r == 1: return n
    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]
    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot
    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])
    return result
def combination_with_repetition_count(n, r):
    return combinations_count(n + r - 1, r)
from collections import deque, Counter # https://docs.python.org/ja/3/library/collections.html#collections.deque
from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest # https://docs.python.org/ja/3/library/heapq.html
from copy import deepcopy, copy # https://docs.python.org/ja/3/library/copy.html
from functools import reduce
from fractions import gcd # Deprecated since version 3.5: Use math.gcd() instead.
def gcds(numbers):
    return reduce(gcd, numbers)
def lcm(x, y):
    return (x * y) // gcd(x, y)
def lcms(numbers):
    return reduce(lcm, numbers, 1)
# about how to set the inputs
    # open(0).read() is a convenient method:
    # ex) n, m, *x = map(int, open(0).read().split())
    #     min(x[::2]) - max(x[1::2])
    # ex2) *x, = map(int, open(0).read().split())
    #     don't forget to add comma after *x if only one variable is used
    # R = lambda: map(int, input().split()) :it's fashionable, isn't it?
    # ex1) n, k = R()
    # ex2) v = list(R())
    # ex3) bc = [list(R()) for i in range(m)]

# R = lambda: map(int, input().split())
s = input()
s = s.replace('A','0')
s = s.replace('BC','1')
s = s.replace('B',' ')
s = s.replace('C', ' ')
l = s.split()
ans = 0
for i in l:
    countbc = 0
    for j in i[::-1]:
        if j == '1':
            countbc += 1
        else:
            ans += countbc

print(ans)

Submission status: Accepted

Solution code:
S = input()
S = S.replace("BC", "D")

c = 0
total = 0

for s in S:
    if s == "A":
        c += 1
    elif s == "D":
        total += c
    else:
        c = 0

print(total)

Submission status: Accepted

Solution code:
from functools import reduce

# 入力
s = input()

# AA..ABC -> BCAA..A に変換するのを繰り返す
ans, _, _ = reduce(
    lambda acc, c: (
        (acc[0], (1 - acc[2]) * acc[1] + 1, 0) if c == 'A' else
        (acc[0], (1 - acc[2]) * acc[1], 1 - acc[2]) if c == 'B' else
        (acc[0] + acc[2] * acc[1], acc[2] * acc[1], 0)
    ),
    s,
    (0, 0, 0)
)

# 出力
print(ans)

Submission status: Accepted

Solution code:
s = input()
s = s.replace('BC','D')

ans = 0
cnta = 0
for n in range(len(s)):
    if s[n] == 'A':
        cnta += 1
    elif s[n] == 'D':
        ans += cnta
    elif s[n] == 'B' or s[n] == 'C':
        cnta = 0

print(ans)

Submission status: Accepted

Solution code:
s = input()
n = len(s)
ans = 0
numa = 0
i = 0
while i < n-1:  # 最後'BC'以外は、最後の文字は関係ないので s[n-1]は不要
    if s[i] == 'A':
        numa += 1   # Aが連続で続く場合は数える
    elif s[i:i+2] == 'BC':
        ans += numa # AAAA と BC を入れ替える回数。またBCが来たら加算する
        i += 1  # BCの場合は、2文字進めるので+1
    else:
        numa = 0
    i += 1
print(ans)

Submission status: Accepted

Solution code:
s = input()
s = s.split('BC')
count = [0]
count_all = 0
Icount = 0

for i in range(0,len(s)-1):
    Icount = 0
    j = 1
    while(j<=len(s[i]) and s[i][-j]=='A'):
        Icount = Icount + 1
        j = j + 1
        
    if (s[i]=='' or s[i]=='A'*len(s[i])):
        Icount = Icount + count[-1]
   
    count.append(Icount)
  
        
count_all = sum(count)  
print(count_all)

Submission status: Accepted

Solution code:
S=input()

cnt=[]

def solve(s):
  pos = len(s)-sum(s)
  ct=0
  res=0
  for i in range(len(s)):
    if s[i]==1:
      res+=(pos+ct-i)
      ct+=1
  return res

n=0
while n < len(S):
  if S[n]=='A':
    cnt.append(1)
    n+=1
  elif (n < len(S)-1) and (S[n]=='B') and (S[n+1]=='C'):
    cnt.append(0)
    n+=2
  else:
    cnt.append(2)
    n+=1

r=0
l=0
ans=0
while l < len(cnt):
  if cnt[l] != 2:
    r=l
    while r<len(cnt) and cnt[r]!=2:
      r+=1
    ans+=solve(cnt[l:r])
    l=r
  else:
    l+=1

    
print(ans)

Submission status: Accepted

Solution code:
s = input()
n = len(s)

ans = 0
cnt = 0

for i in range(n-1):
    if s[i] == "A":
        cnt += 1
    if s[i]+s[i+1] == "BC":
        ans += cnt
    if s[i]+s[i+1] in ("AC","BA","BB","CC"):
        cnt = 0

print(ans)

Submission status: Accepted

Solution code:
s = input()
ans = 0
cntA = 0
for i in range(0, len(s) - 1):
    if s[i] == 'A':
        cntA += 1
    elif s[i: i + 2] == "BC":
        ans += cntA
    elif i > 0 and s[i - 1: i + 1] == "BC":
        continue
    else:
        cntA = 0
print(ans)
# print(*data, sep='\n')

Submission status: Accepted

Solution code:
S = input().replace('BC', 'D')
ans, n = 0, 0

for s in S:
    if s == 'A':
        n += 1
    elif s == 'D':
        ans += n
    else:
        n = 0
print(ans)

Submission status: Accepted

Solution code:
s = input().replace("BC", 'X')
a, x, ans = 0, 0, 0
for char in s:
    if char == 'A':
        a += 1
    elif char == 'X':
        ans += a
    else:
        a, x = 0, 0
print(ans)

Submission status: Accepted

Solution code:
s = str(input())
s = s.replace("BC","X")

retn = 0
cnt = 0

for i in range(len(s)):

    if (s[i] == "A"):
        cnt += 1
    elif (s[i] == "X"):
        retn += cnt
    else:
        cnt = 0

print(retn)

Submission status: Accepted

Solution code:
s = input()
s= s.replace('BC','D')
a=0
d=0
ans=0
t=''
for i in range(len(s)):
    if s[i] =='A':
        a+=1
    elif s[i]=='D':
        ans+=a
    else:
        a=0
print(ans)

Submission status: Accepted

Solution code:
import copy
S = input()
#print(S)
S2 = S.replace("BC", "D")
#print(S2)
count = 0
Acount = 0
Dcount = 0
for i in range(len(S2)):
    if S2[i] == 'A' or S2[i] == 'D':
        if S2[i] == 'A':
            Acount += 1
        else:
            count += Acount
    else:
        Acount = 0
    #print(count, Acount, S2[i])
print(count)

Submission status: Accepted

Solution code:
s = input().strip()
n = len(s)
ret = 0
a = 0
i = 0
while i < n:
    if s[i] == 'A':
        a += 1
        i += 1
    elif s[i] == 'B':
        if i < n - 1 and s[i + 1] == 'C':
            ret += a
            i += 2
        else:
            a = 0
            i += 1
    else:
        a = 0
        i += 1
print(ret)

Submission status: Accepted

Solution code:
S = input()+"D"

i = 0
ans = 0
A = 0
while i < len(S)-1:
    if A > 0 and S[i] == "B" and S[i+1] == "C":
        i += 2
        ans += A
    elif S[i] == "A":
        A += 1
        i += 1
    else:
        A = 0
        i += 1
print(ans)

Submission status: Accepted

Solution code:
s = input()
n = len(s)
st = ''
i = 0
while i < n:
    if i < n - 1 and s[i] == 'B' and s[i + 1] == 'C':
        st += 'D'
        i += 1
    else:
        st += s[i]
    i += 1
ans = 0
ac = 0
for c in st:
    if c in ('B', 'C'):
        ac = 0
    elif c == 'A':
        ac += 1
    elif c == 'D':
        ans += ac
print(ans)

Submission status: Accepted

Solution code:
s=input()

S=[s[0]]

for i in range(1,len(s)):
    if S[len(S)-1]=="B" and s[i]=="C":
        S[len(S)-1]="D"
    else:
        S.append(s[i])
#print(S)

L=[]
if S[len(S)-1]=="D":
    L.append(1)
else:
    L.append(0)
    
for i in range(1,len(S)):
    if S[len(S)-1-i]=="D":
        L.append(L[len(L)-1]+1)
    elif S[len(S)-1-i]=="A":
        L.append(L[len(L)-1])
    else:
        L.append(0)
L=L[::-1]
#print(L)
ANS=0
for i in range(len(S)):
    if S[i]=="A":
        ANS+=L[i]
print(ANS)

Submission status: Accepted

Solution code:
s = input().strip().replace('BC', 'D')
n = len(s)

count = 0
a_count = 0
for i in range(n):
  if s[i] == 'A':
    a_count += 1
  elif a_count > 0 and s[i] == 'D':
    count += a_count
  else:
    a_count = 0

print(count)

Submission status: Accepted

Solution code:
s=input()
s=s.replace("BC","D")
totalCount=0
count=0
for char in s:
    if char=="A":
        count+=1
    elif char=="D":
        totalCount+=count
    else:
        count=0
print(totalCount)

Submission status: Accepted

Solution code:
# coding: utf-8
import os
import time
import re
import math

def main():
    s=input().replace("BC","D")
    max=0
    acount=0
    for a in range(len(s)):
        if s[a]=='D':
            max+=acount
        elif s[a]=='A':
            acount+=1
        else:
            acount=0
    print(max)



start=time.time();
main()
#print(time.time()*1000-start*1000)

Submission status: Accepted

Solution code:
# coding: utf-8
import os
import time
import re
import math

def main():
    s=input().replace("BC","D")
    max=0
    acount=0
    for a in s:
        if a=='D':
            max+=acount
        elif a=='A':
            acount+=1
        else:
            acount=0
    print(max)
start=time.time();
main()
#print(time.time()*1000-start*1000)

Submission status: Accepted

Solution code:
s=input()
ans=0
cnt=0
flag=0
for i in range(len(s)-1,-1,-1):
  if flag==0:
    if s[i]=='C':
      flag=1
    elif s[i]=='A':
      ans+=cnt
    elif s[i]=='B':
      cnt=0
  elif flag==1:
    if s[i]=='B':
      flag=0
      cnt+=1
    elif s[i]=='C':
      cnt=0
    elif s[i]=='A':
      flag=0
      cnt=0
print(ans)

Submission status: Accepted

Solution code:
s = input()
s = s.replace("BC","D")
count_Sum = 0
countA = 0
countD = 0

for i in range(len(s)):
    if s[i] == "A" and countD == 0:
        countA += 1
    elif s[i] == "D":
        countD += 1
        if i+1 == len(s):
            count_Sum += countA*countD
    else:
        count_Sum += countA*countD
        if s[i] == "B" or s[i] =="C":
            countA = 0
            countD = 0
        else:
            countA += 1
            countD = 0
print(count_Sum)

Submission status: Accepted

Solution code:
S = input()
S = S.replace('BC', 'D')
length = len(S)

ans = 0
count_a = 0
for i in range(length):
  c = S[i]

  if c == 'A':
    count_a += 1
  elif c == 'D':
    ans += count_a
  else:
    count_a = 0

print(ans)

Submission status: Accepted

Solution code:
S=input()
ans=0
a=0
i=0
while i<len(S):
    if S[i]=='A':
        a+=1
        i+=1
    elif S[i:i+2]=='BC':
        ans+=a
        i+=2
    else:
        a=0
        i+=1
    #print(a,ans)
print(ans)

Submission status: Accepted

Solution code:
# -*- Coding: utf-8 -*-
#import numpy as np

def count(s):
	i = 0
	a_cnt = 0
	cnt = 0
	while i < len(s):
		if s[i] == 'A':
			a_cnt += 1
		if s[i] =='D':
			cnt += a_cnt

		i += 1

	return cnt



originalS = raw_input()
originalS = originalS.replace('BC', 'D')
originalS = 'B'+originalS+'B'	


idx = []
i = 0

while i < len(originalS):
	if (originalS[i] == 'B')|(originalS[i] == 'C'):
		idx.append(i)
	i += 1


Substr = []

i = 0
while i < len(idx)-1:
	if idx[i+1]-idx[i]!=1:
		Substr.append(originalS[idx[i]+1:idx[i+1]])

	i += 1

ans = 0
for c in Substr:
	ans += count(c)

print ans

Submission status: Accepted

Solution code:
s = input().replace("BC","D")

res = 0
num = 0
for i in s:
    if i == "B" or i == "C":
        num = 0
    elif i == "A":
        num += 1
    else:
        res += num

print(res)

Submission status: Accepted

Solution code:
s = input().replace("BC","D")

def main():
    res = 0
    num = 0
    for i in s:
        if i == "B" or i == "C":
            num = 0
        elif i == "A":
            num += 1
        else:
            res += num
    
    print(res)



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
s = input()

count = 0
counta = 0
for i in range(len(s)):
    if s[i] == "A":
        if s[i-1] != "B" or i == 0:
            counta += 1
        else:
            counta = 1
    elif s[i] == "B":
        if s[i-1] == "B":
            counta = 0
    else:
        if s[i-1] == "B":
            count += counta
        else:
            counta = 0
print(count)

Submission status: Accepted

Solution code:
from sys import stdin

def main():
    S = input()

    S_ = S.replace('BC', 'D')
    ans, cnt = 0, 0
    for s in S_[::-1]:
        if s == 'D':
            cnt += 1
        elif s == 'A':
            ans += cnt
        else:
            cnt = 0
    print(ans)

input = lambda: stdin.readline().rstrip()
main()

Submission status: Accepted

Solution code:
s = input()

count = 0
ans = 0

ss = s.replace('BC','X')

flag = 0

for i in ss:
    if i == 'A':
        flag += 1
    elif i == 'X':
        ans += flag
    else:
        flag = 0

print(ans)

Submission status: Accepted

Solution code:
import math
import numpy as np
import re


def inputs(): return [int(s) for s in input().split()]


def main():
    s = input()
    cnt = 0
    s = s.replace('A', '1').replace('BC', '0')
    arr = re.split('[A-C]', s)
    arr = [list(x) for x in arr]

    for a in arr:
        tmp = 0
        for i in a:
            i = int(i)
            tmp += i
            if i is 0:
                cnt += tmp

    return cnt


if __name__ == '__main__':
    print(main())

Submission status: Accepted

Solution code:
import math
import numpy as np
import re


def inputs(): return [int(s) for s in input().split()]


def main():
    s = input()
    cnt = 0
    s = s.replace('A', '1').replace('BC', '0')
    arr = re.split('[A-C]', s)
    arr = [list(x) for x in arr]
    flag = True
    while flag:
        flag = False
        for a in arr:
            tmp = 0
            for i in a:
                i = int(i)
                tmp += i
                if i is 0:
                    cnt += tmp

    return cnt


if __name__ == '__main__':
    print(main())

Submission status: Accepted

Solution code:
s = input()
s = s.replace('BC', 'D')

a = 0
cnt = 0
for x in s:
    if x == 'A':
        a += 1
    elif x == 'D':
        cnt += a
    else:
        a = 0

print(cnt)

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
from collections import deque
from heapq import heappush,heappop
import re

def int_raw():
    return int(input())
 
def ss_raw():
    return input().split()
 
def ints_raw():
    return tuple(map(int, ss_raw()))


DIV=10**9+7

#N,A,B,C = ints_raw()
ESP_C = "$"
S=input()

def main():
    nS = S.replace("BC",ESP_C)
    ans =0
    a_buf =0
    for idx,c in enumerate(nS):
        if c == "A":
            a_buf+=1
        elif c == ESP_C:
            ans+=a_buf
        else:
            a_buf =0
    return ans

print(main())

Submission status: Accepted

Solution code:
s=list(input())

i=0
j=0
ans=0
z=[]
while i!=len(s)-1:
    try:
        if s[i]=="B" and s[i+1]=="C":
            z.append(1)
            i=i+2

        else:
            if s[i]=="A":
                z.append(2)
                i=i+1

            else:
                z.append(0)
                i=i+1

    except:
      break

ans=0
i=0
r1=0


#print(z)
#ｚ＝判定数列

while i!=len(z):
    if z[i]==2:#"A"
         r1=r1+1

    elif z[i]==1:#"BC"
        ans=ans+r1

    else:#"gomi"
        r1 = 0


    i=i+1
print(ans)

Submission status: Accepted

Solution code:
S = input()


ans = 0
i = 0
running_A_count = 0
while i + 1 < len(S):
    if S[i] == "A":
        running_A_count += 1
    elif S[i] == "B" and S[i+1] == "C":
        ans += running_A_count
        i += 1
    else:
        running_A_count = 0
    
    i += 1






print(ans)

Submission status: Accepted

Solution code:
import re
S = input()
N1 = S.replace('A','0').replace('BC','1')
S_li = re.split('B|C',N1)
 
count = 0
for l in S_li:
    a = sum([i for i,x in enumerate(l) if '1' in x])
    su=sum([x for x in range(l.count('1'))])
    count += (a-su)
print(str(count))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)
INTMAX = 9223372036854775807
INTMIN = -9223372036854775808
MOD = 1000000007
def POW(x, y): return pow(x, y, MOD)
def INV(x, m=MOD): return pow(x, m - 2, m)
def DIV(x, y, m=MOD): return (x * INV(y, m)) % m
def LI(): return [int(x) for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LS(): return input().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()


s = input().replace('BC', 'D')

cnt = 0
res = 0
for i in range(len(s)):
    if s[i] == 'A':
        cnt += 1
    elif s[i] == 'D':
        res += cnt
    else:
        cnt = 0
print(res)

Submission status: Accepted

Solution code:
s = input()
 
ans = 0
s = s.replace("BC","D")
cnt_A = 0
 

for i in s:
    if i == "A":
        cnt_A += 1
    elif i == "D":
        ans += cnt_A
    else:
        cnt_A = 0

print(ans)

Submission status: Accepted

Solution code:
import re

s = input()
s = re.sub('BC', 'D', s)

ans = 0
cnt = 0
for c in s:
    if c == 'A':
        cnt += 1
    elif c == 'D':
        ans += cnt
    else:
        cnt = 0

print(ans)

Submission status: Accepted

Solution code:
import re

s = input()
s = s.replace('BC', 'D')
ss = [c for c in re.split('[BC]', s) if c != '']

sum = 0
for s in ss:
  na = 0
  for c in s:
    if c == 'A':
      na += 1
    else:
      sum += na

print(sum)

Submission status: Accepted

Solution code:
s = input()
s2 = s.replace("BC", "D")

A, ans = 0, 0

for i in s2:
    if i == "A":
        A += 1
    elif i == "D":
        ans += A
    else:
        A = 0

print(ans)

Submission status: Accepted

Solution code:
def f(ss):
  n=len(ss)
  ct,res=0,0
  for i in range(n):
    if ss[i]=="x":
      ct+=1
    else:
      res+=ct
  return res
s=input()
s=s.replace("BC","y")
s=s.replace("A","x")
s+="z"
ans=0
chk=""
for i in range(len(s)):
  if s[i]=="x" or s[i]=="y":
    chk+=s[i]
  else:
    ans+=f(chk)
    chk=""
print(ans)

Submission status: Accepted

Solution code:
s=raw_input()
l=len(s)

i=0
cnt=0
ans=0
while i<l:
	x=s[i]
	if x=="A":
		i+=1
		cnt+=1
	elif i+1<l and s[i]=="B" and s[i+1]=="C":
		i+=2
		ans+=cnt
	else:
		i+=1
		cnt=0


print ans

Submission status: Accepted

Solution code:
###template###
import sys
def input(): return sys.stdin.readline().rstrip()
def mi(): return map(int, input().split())
###template###

s = input()
if not ('ABC' in s):
  print(0)
  exit()

from collections import deque
S = deque(maxlen=200000)
tmp = 'C'
for ss in s:
  if tmp == 'B' and ss == 'C':
    S.pop()
    S.append('D')
    tmp = 'C'
  elif ss == 'C':
    S.append('B')
    tmp = 'C'
  else:
    S.append(ss)
    tmp = ss

ans = 0
ihavea = 0
#保持してる文字列
Acnt = 0
while 1:
  try:
    tmp = S.popleft()
  except:
    print(ans)
    exit()
  if tmp=='B':
    ihavea = 0
    Acnt = 0
    continue
  if ihavea == 0 and tmp=='A':
    ihavea = 1
    Acnt += 1
    continue
  if ihavea == 1 and tmp=='A':
    ihavea = 1
    Acnt += 1
    continue
  if ihavea == 1 and tmp=='D':
    ihavea = 1
    ans += Acnt
    #Aはそのまま引き継ぐ
    continue

Submission status: Accepted

Solution code:
s = input().replace('BC', 'D')
ans = 0
cnt = 0

for c in s:
    if c == 'A':
        cnt += 1
    elif c == 'D':
        ans += cnt
    else:
        cnt = 0
print(ans)

Submission status: Accepted

Solution code:
S=input()
c=0
ans=0
S=S.replace('BC','X')
for i in range(len(S)):
    if S[i]=='A':
        c+=1
    elif S[i]=='X':
        ans+=c
    else:
        c=0
print(ans)

Submission status: Accepted

Solution code:
s = input()
s = s.replace("BC","X")
ans = []
c = 0

for i in range(1,len(s)+1):
    if s[-1 * i] == "X":
        c += 1
    elif s[-1 * i] == "A":
        ans.append(c)
    else:
        c = 0
print(sum(ans))

Submission status: Accepted

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


def solve(s: str):
    
    s = s.replace('BC', 'X')

    ans = 0
    cur = 0
    for i in range(len(s)):
        if(s[i] == 'A'):
            cur += 1
        elif(s[i] == 'X'):
            ans += cur
        else:
            cur = 0    

    print(ans)
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    s = next(tokens)  # type: str
    solve(s)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
a = input()
b = []
count = 0
a = a.replace('BC','D')
for i in range(1,len(a)+1):
    if a[-i] == 'D':
        count += 1
    elif a[-i] == 'A':
        b.append(count)
    else:
        count = 0
print(sum(b))

Submission status: Accepted

Solution code:
s = input()

N = len(s)

i = 0
result = 0
count_a = 0
count_bc = 0

while i < N-2:
    if s[i] == 'A':
        while s[i] == 'A' and i < N-2:
            count_a += 1
            i += 1
        
        if i >= N-1:
            break
                        
        while s[i] == 'B' and s[i+1] == 'C':
            count_bc += 1
            i += 2
            if i >= N-1:
                break
        
        result += count_a * count_bc

        if i >= N-1:
            break
        
        if count_bc > 0 and s[i] == 'A':
            count_a = count_a
        else:
            count_a = 0
        
        count_bc = 0
                    
    else:
        i += 1
        
print(result)

Submission status: Accepted

Solution code:
s=input()
arr=[]
i=0
while i<(len(s)):
    if s[i]=='A':
        arr.append('A')
        i+=1
        continue
    else:
        if (i+1)<len(s):
            if s[i:i+2]=='BC':
                arr.append('D')
                i+=2
                continue
            else:
                arr.append(s[i])
                i+=1
                continue
        else:
            arr.append(s[i])
            i+=1
temp=''.join(arr)
a=False
count=0
ans=0
# print(temp)
for i in range(len(temp)):
    if not a:
        if temp[i]=='A':
            count+=1
            a=True
    else:
        if temp[i]=='D':
            ans+=count
        elif temp[i]=='A':
            count+=1 
        else:
            # ans+=count
            # count-=1
            count=0 
            a=False
    # print(count,"iter ",i)
print(ans)