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:
#!/usr/bin/env python3
##### Binary Indexed Tree #####
class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0]*(n+1)

    def __iter__(self):
        psum = 0
        for i in range(self.size):
            csum = self.sum(i+1)
            yield csum - psum
            psum = csum
        raise StopIteration()

    def __str__(self):  # O(nlogn)
        return str(list(self))

    def sum(self, i):
        # [0, i) の要素の総和を返す
        if not (0 <= i <= self.size): raise ValueError("error!")
        s = 0
        while i>0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        if not (0 <= i < self.size): raise ValueError("error!")
        i += 1
        while i <= self.size:
            self.tree[i] += x
            i += i & -i

    def __getitem__(self, key):
        if not (0 <= key < self.size): raise IndexError("error!")
        return self.sum(key+1) - self.sum(key)

    def __setitem__(self, key, value):
        # 足し算と引き算にはaddを使うべき
        if not (0 <= key < self.size): raise IndexError("error!")
        self.add(key, value - self[key])

# 転倒数
def mergecount(A: list):
    if not A:
        return 0
    bit = Bit(max(A) + 1)
    cnt = 0
    for i, a in enumerate(A):
        cnt += i - bit.sum(a+1)
        bit.add(a, 1)
    return cnt

import re
print(sum(mergecount([*map(int, i)]) for i in re.split("[BC]", input().replace("A", "1").replace("BC", "0"))))

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    s = input()
    t = s.replace("BC", "X")

    ans = 0
    cnt = 0

    for char in t[::-1]:
        if char == "X":
            cnt += 1
        elif char == "A":
            ans += cnt
        else:
            cnt = 0

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    s = SS()

    # AがBCを乗り越えて右に進むイメージ
    # それぞれのAに対して右側に連続したBCがいくつあるか
    ans = 0
    len_s = len(s)
    cnt = 0
    i = 0
    while i < len_s:
        if s[i] == 'A':
            cnt += 1
            i += 1
        elif i + 1 < len_s and s[i] == 'B' and s[i+1] == 'C':
            ans += cnt
            i += 2
        else:
            cnt = 0
            i += 1
            
    print(ans)

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    s = SS()

    # AがBCを乗り越えて右に進むイメージ
    # それぞれのAに対して右側に連続したBCがいくつあるか
    ans = 0
    len_s = len(s)
    cnt = 0
    i = 0
    while i < len_s:
        # print(s[i], cnt)
        if s[i] == 'A':
            cnt += 1
            i += 1
        elif i + 1 < len_s and s[i] == 'B' and s[i+1] == 'C':
            ans += cnt
            i += 2
        else:
            cnt = 0
            i += 1
            
    print(ans)

if __name__ == '__main__':
    resolve()

Submission status: Accepted

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

ans, cnta = 0, 0
for i in range(len(s)):
    if s[i] == 'A':
        cnta += 1
    elif s[i] == 'a':
        ans += cnta
    else:
        cnta = 0
print(ans)

Submission status: Accepted

Solution code:
s = input()

ans, cnta = 0, 0
for i in range(len(s)):
    if s[i] == 'A':
        cnta += 1
    elif s[i:i + 2] == 'BC':
        ans += cnta
    elif s[i - 1:i + 1] != 'BC':
        cnta = 0
print(ans)

Submission status: Accepted

Solution code:
s = list(input())
li = []
n = len(s)
ans = 0
b = False
for i in range(n-1):
    if b:
        b = False
        continue
    if s[i] + s[i+1] == 'BC':
        li.append('D')
        b = True
    if s[i] == 'B' and s[i+1] != 'C':
        li.append('E')
    if s[i] == 'C':
        li.append('E')
    if s[i] == 'A':
        li.append('A')
cnt = 0
for i in range(len(li)):
    if li[i] == 'A':
        cnt += 1
    elif li[i] == 'E':
        cnt = 0
    else:
        ans += cnt
print(ans)

Submission status: Accepted

Solution code:
S = input()

rlt = 0
b = ''
tA = 0
A = 0
BC = 0
for s in S:
  if s == 'A':
    if b == 'A':
      tA += 1
    elif b == 'B':
      rlt += A*BC
      tA = 1
      A = 0
      BC = 0
    else:
      rlt += A*BC
      tA = A + 1
      A = 0
      BC = 0
  elif s == 'B':
    if b == 'B':
      rlt += A*BC
      tA = 0
      A = 0
      BC = 0
  elif s == 'C':
    if b == 'B':
      A += tA
      tA = 0
      BC += 1
    else:
      rlt += A*BC
      tA = 0
      A = 0
      BC = 0
  b = s

rlt += A*BC
  
print(rlt)

Submission status: Accepted

Solution code:
#coding: utf-8
#!/home/nicetacks/.pyenv/shims/python3

s = input()

while "BC" in s:
    s = s.replace("BC", "D")

ret  = 0
numA = 0
for i in range(len(s)):
    if s[i] == "A":
        numA += 1
    elif s[i] == "D":
        ret += numA
    else:
        numA = 0

print(ret)

Submission status: Accepted

Solution code:
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

s = input()
ans = 0
count = 0
i = 0
while i < len(s) - 1:
    if s[i]== 'A':
        count += 1
        i += 1
    elif s[i:i+2] == 'BC':
        ans += count
        i += 2
    else:
        count = 0
        i += 1
print(ans)

Submission status: Accepted

Solution code:
S = str(input())

count =  0
AP_streak = 0
P_pos = []
P_count = 0

S=S.replace('BC', 'P')

N = len(S)

for i in range (0, N):
	V = S[i]
	if V != 'P' and V!= 'A':
		count+=sum(P_pos)-(P_count*(P_count+1))//2
		AP_streak = 0
		P_pos = []
		P_count = 0
	if V == 'A':
		AP_streak+=1
	if V == 'P':
		if AP_streak > 0:
			AP_streak+=1
			P_count+=1
			P_pos.append(AP_streak)

count+=sum(P_pos)-(P_count*(P_count+1))//2

print(count)

Submission status: Accepted

Solution code:
# 実装する
# BCをXとしたとき、AとXだけが含まれる部分列は操作終了後に左側にX右側にAが詰まる
# AXXAAXのときはXXXAAAになる Aが右側に移動すると考える
# Aの移動距離 部分列長6にAが3個ある それぞれのAの初期位置から最終的に移動する位置までの距離
# （Aの初期位置位置[1 4 5]が最終的に[4 5 6]にくるのでその差）
# しゃくとりっぽい操作でいけそう
s = input()
t = s.replace("BC", "X", len(s))
ans = 0
left, right = 0, 0
while left < len(t):
    # 部分列の左端を見つける
    if t[left] not in ["A", "X"]:
        left += 1
        continue
    a_indicies = []
    a_count = 0
    a_idx = 0
    if t[left] == "A":
        a_indicies.append(a_idx)
        a_count += 1
    right = left + 1
    a_idx += 1
    while right < len(t) and t[right] in ["A", "X"]:
        if t[right] == "A":
            a_indicies.append(a_idx)
            a_count += 1
        right += 1
        a_idx += 1
    # leftからrightまでの部分列にAしか含まれていないorXしか含まれていない場合は考えない
    if right - left != a_count and a_count != 0:
        for i in range(a_count):
            ans += ((right - left) - (a_count - i)) - a_indicies[i]  # 適当
    left = right + 1
print(ans)

Submission status: Accepted

Solution code:
s = input()
n = len(s)
d = [s[0]]
for i in range(1,n):
  if s[i]=="C" and s[i-1]=='B':
    d.pop()
    d.append("x")
  else:
    d.append(s[i])
q = "".join(d)
cou = 0
cou_a = 0
l = len(q)
for i in range(l):
  if q[i]=="A":
    cou_a += 1
  elif q[i]=="x":
    cou +=  cou_a
  else:
    cou_a = 0
print(cou)

Submission status: Accepted

Solution code:
def f():
  ans,c=0,0
  for t in input().replace('BC','y'):
    if t=='y':ans+=c
    elif t=='A':c+=1
    else:c=0
  print(ans)
if __name__ == "__main__":f()

Submission status: Accepted

Solution code:
def f():
    ans,c=0,0
    for t in input().replace('BC','y').replace('A','x'):
        if t=='y':ans+=c
        elif t=='x':c+=1
        else:c=0
    print(ans)
if __name__ == "__main__":
    f()

Submission status: Accepted

Solution code:
ans=0
for x in input().replace('BC','y').replace('A','x').replace('B',' ').replace('C',' ').split():
    c=0
    for t in x:
        if t=='y':
            ans+=c
        else:c+=1
print(ans)

Submission status: Accepted

Solution code:
def solve(s):
    n = len(s)
    res = 0
    i = 0
    num = 0
    while i < n-1:
        if s[i] == "A":
            num += 1
            i += 1
        elif s[i:i+2] == "BC":
            res += num
            i += 2
        else:
            num = 0
            i += 1
    return res

s = input()
print(solve(s))

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline


def main():
    S = input().rstrip()

    ans = 0
    A_count = 0
    i = 0
    N = len(S)
    while i < N - 1:
        if S[i] == "A":
            A_count += 1
            i += 1
        elif S[i:i + 2] == "BC":
            ans += A_count
            i += 2
        else:
            A_count = 0
            i += 1

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
s=input()

s=list(s.replace("BC", "D"))
ans=0
cnt_a=0
for i in range(len(s)):
    if s[i]=="A":
        cnt_a+=1
    elif s[i]=="D":
        ans+=cnt_a
    else:
        cnt_a=0

print(ans)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, log
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
from decimal import *

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

cnt = 0
ans = 0
for x in s:
	if x == "A":
		cnt += 1
	elif x == "D":
		ans += cnt
	else:
		cnt = 0

print(ans)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, log
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
from decimal import Decimal
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
from decimal import *

s = input()
t = ""

i = 0
while i < len(s):
	if s[i:i+2] == "BC":
		t += "D"
		i += 2
	else:
		t += s[i]
		i += 1

D_cnt = []
cnt = 0
for x in t[::-1]:
	if x == "D":
		cnt += 1
		D_cnt.append(cnt)
	elif x == "A":
		D_cnt.append(cnt)
	else:
		cnt = 0
		D_cnt.append(cnt)

D_acc = D_cnt[::-1]

ans = 0
for i in range(len(t)):
	if t[i] == "A":
		ans += D_acc[i]

print(ans)

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


s = input()
n = len(s)
v = []
i = 0
tmp = []
while i<n:
    if s[i]=="A":
        tmp.append(0)
        i += 1
    elif i<n-1 and s[i]=="B" and s[i+1]=="C":
        tmp.append(1)
        i += 2
    else:
        i += 1
        if tmp:
            v.append(tmp)
        tmp = []
if tmp:
    v.append(tmp)
ans = 0
for l in v:
    val = 0
    for c in l:
        if c==1:
            ans += val
        else:
            val += 1
print(ans)

Submission status: Accepted

Solution code:
S = input().replace('BC', 'D')
ans = 0
cnt = 0
for s in S:
    if s=='A':
        cnt += 1
    elif s=='D':
        ans += cnt
    else:
        cnt = 0
print(ans)

Submission status: Accepted

Solution code:
s=input().replace('BC','D')
a=[]
b=''
for c in s:
    if c=='B' or c=='C':
        a.append(b)
        b=''
    else:
        b+=c
a.append(b)
ans=0
for i in a:
    ac=0
    for j in i:
        if j=='A':
            ac+=1
        else:
            ans+=ac
print(ans)

Submission status: Accepted

Solution code:
def main():
  S = str(input())
  s = []
  i = 0
  while i <= len(S)-1:
    if i == len(S)-1:
      s.append(S[i])
      break
    if S[i] == "B" and S[i+1] == "C":
      s.append("D")
      i += 2
    else:
      s.append(S[i])
      i += 1
  ans = 0
  flag = True
  for i in range(len(s)-1, -1, -1):
    if flag and s[i] == "D":
      posi = i
      flag = False
    if not flag and s[i]=="A":
      ans += posi-i
      posi-= 1
    if s[i] == "B" or s[i] == "C":
      flag = True
  print(ans)
  
  
if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
s = input().replace("BC", "D")
a = 0
c = 0
for i in s[::-1]:
    if i == "D":
        c += 1
    elif i == "A":
        a += c
    else:
        c = 0
print(a)

Submission status: Accepted

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

ans = 0
cnt = 0
for i in s[::-1]:
    if i == "D":
        cnt += 1
    elif i == "A":
        ans += cnt
    else:
        cnt = 0



print(ans)

Submission status: Accepted

Solution code:
def test(s):

	res = 0
	aAdd = 0
	last = ''
	tmp = ''
	for i in xrange(len(s)):
		if tmp and tmp > i:
			continue
		if s[i] == 'A':
			aAdd += 1
		elif s[i:i+2] == 'BC':
			# print aAdd
			res = res + aAdd
			tmp = i + 2
		else:
			aAdd = 0
			last = s[i]


	return res
s=raw_input()
print test(s)

Submission status: Accepted

Solution code:
s = raw_input()
count = 0
num = 0
i = 0
length = len(s)
while i < length:
	if s[i] == 'A':
		num += 1
		i += 1
	elif i+1 < len(s) and s[i] == 'B' and s[i+1] == 'C':
		count += num
		i += 2
	else:
		num = 0
		i += 1
print count

Submission status: Accepted

Solution code:
s = input().replace('BC', 'X')
cnt_a = 0
ans = 0
for c in s:
    if c == 'A':
        cnt_a += 1
    if c == 'X':
        ans += cnt_a
    if c in 'BC':
        cnt_a = 0
print(ans)

Submission status: Accepted

Solution code:
s = raw_input()

count = 0
a = 0
i = 0
l = len(s)
while i < len(s):
    if s[i] == 'A':
        a += 1
        i += 1
        continue

    if s[i] == 'B' and i < l - 1 and s[i + 1] == 'C':
        count += a
        i += 2
    else:
        a = 0
        i += 1

print count

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_nl = lambda: list(map(int, readline().split()))
in_na = lambda: map(int, read().split())
in_s = lambda: readline().rstrip().decode('utf-8')


def t(S):

    N = len(S)

    a = [0] * (N + 1)
    d = [0] * (N + 1)
    for i in range(N):
        if S[i] == 'A':
            a[i + 1] = 1
        else:
            d[i + 1] = 1

    for i in range(N):
        a[i + 1] += a[i]
        d[i + 1] += d[i]

    ans = 0
    for i in range(1, N):
        if S[i] == 'D':
            ans += a[i]

    return ans


def main():

    S = in_s()
    S = S.replace('BC', 'D')
    S = S.replace('B', ' ')
    S = S.replace('C', ' ')

    ans = 0
    for ts in S.split():
        ans += t(ts)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from itertools import accumulate

s = input()
l = s.split('BC')[:-1]
l = l[::-1]

ans = 0
i = 0

while i < len(l):
    anum = []
    flag = True
    while flag and i < len(l):
        M = len(l[i])
        tmp = 0
        for j in range(M):
            if l[i][M-j-1] == 'A':
                tmp += 1
            else:
                flag = False
                break
        anum.append(tmp)
        if flag:
            i += 1
    ans += sum(accumulate(anum[::-1]))
    i += 1
print(ans)

Submission status: Accepted

Solution code:
s=input()
i=1
new=[s[0]]
while i<len(s):
    if s[i]=="C" and s[i-1] == "B":
        new.pop()
        new.append("K")
    else:
        new.append(s[i])
    i+=1

cnt=0
ans=0
for i in range(len(new)-1,-1,-1):
    if new[i]=="A" and cnt > 0:
        ans+=cnt
    elif new[i]=="K":
        cnt+=1
    else:
        cnt=0
    
print(ans)

Submission status: Accepted

Solution code:
s=input()
t=''
i=0
while(i<len(s)):
    if i<len(s)-1 and s[i:i+2]=='BC':
        t+='D'
        i+=2
    else:
        t+=s[i]
        i+=1
t=t[::-1]
N=len(t)
i=0
ans=0
while(i<N):
    if t[i]=='D':
        j=i
        cnt=0
        while(j<N and t[j]!='B' and t[j]!='C'):
            if t[j]=='D':
                cnt+=1
            else:
                ans+=cnt
            j+=1
        i=j
    i+=1
print(ans)

Submission status: Accepted

Solution code:
def main():
    S = list(input())
    N = len(S)
    if N <= 2:
        print(0)
        exit()
    T = []
    flag = False
    for i in range(N-1):
        if flag:
            flag = False
            continue

        if S[i] == 'B' and S[i+1] == 'C':
            T.append('D')
            flag = True
        else:
            T.append(S[i])
        
    if not (S[i-2] == 'B' and S[i-1] == 'C'):
        T.append(S[i-1])
    
    M = len(T)
    d = [0] * T.count('D')
    ans = 0
    a = 0
    for i in range(M):
        if T[i] == 'A':
            a += 1
        elif T[i] == 'D':
            ans += a
        else:
            a = 0
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
s = input()
ans = 0
cnt = 0
idx = len(s)

while idx >= 0:
    if s[idx - 2 : idx] == "BC":
        cnt += 1
        idx -= 2
    elif s[idx - 1 : idx] == "A":
        ans += cnt
        idx -= 1
    else:
        idx -= 1
        cnt = 0

print(ans)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    S = input().replace("BC", "D")

    res = 0
    cnt = 0
    for s in S:
        if s == "A":
            cnt += 1
        elif s == "D":
            res += cnt
        else:
            cnt = 0
    print(res)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
#!/usr/bin python3
# -*- coding: utf-8 -*-

def main():
    S = input()
    S = S.replace('BC','Z')
    S = S.replace('B',' ')
    S = S.replace('C',' ')
    S = S[::-1]
    S = S.split()
    ret = 0
    for s in S:
        zcn = 0
        for si in s:
            zcn += (si == 'Z')
            ret += zcn * (si == 'A')
    print(ret)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
S = input()
S = S.replace("BC", "D")
segs = []
prev = "a"
for c in S:
    if c in "AD":
        if prev not in "AD":
            segs.append([c])
        else:
            segs[-1].append(c)
    prev = c

ans = 0
for seg in segs:
    pos = []
    for i in range(len(seg)):
        if seg[i] == "D":
            pos.append(i)
    for i, p in enumerate(pos):
        ans += p - i

print(ans)

Submission status: Accepted

Solution code:
s = input()
l = s.replace("BC","D").replace("B"," ")
L = l.replace("C"," ").split()
ans = 0
for i in L:
    numa = 0
    for j in i:
        if j == "A":
            numa += 1
        else:
            ans += numa
print(ans)

Submission status: Accepted

Solution code:
# input()
# int(input())
# map(int, input().split())
# list(map(int, input().split()))
# list(map(int, list(input()))) # スペースがない数字リストを読み込み
import math
import fractions
import sys
import bisect
import heapq  # 優先度付きキュー(最小値取り出し)
import collections
from collections import Counter
from collections import deque
import pprint

sr = lambda: input()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

"""nを素因数分解"""
"""2以上の整数n => [[素因数, 指数], ...]の2次元リスト"""
def factorization(n):
    arr = []
    temp = n
    if n == 1:
        return arr

    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr

# a^n
def power(a,n,mod):
    x = 1
    while n:
        if n & 1:
            x *= a % mod
        n >>= 1
        a *= a % mod
    return x % mod

# n*(n-1)*...*(l+1)*l
def kaijo(n, l, mod):
    if n == 0:
        return 1
    a = n
    tmp = n-1
    while(tmp >= l):
        a = a*tmp%mod
        tmp -= 1
    return a

inf = 10**18
mod = 10**9+7

s = input()
ss = []
ind = 0
while ind < len(s)-1:
    if s[ind] == 'B' and s[ind+1] == 'C':
        ss.append('D')
        ind+=2
    else:
        ss.append(s[ind])
        ind+=1
if ind == len(s)-1:
    ss.append(s[ind])
ind = 0
A = 0
ans = 0
while ind < len(ss):
    if ss[ind] == 'A':
        A+=1
    elif ss[ind] == 'D':
        ans+=A
    else:
        A = 0
    ind+=1
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
s = input()
s = s.replace("BC", "D")
acnt = 0
mode = 1
ans = 0
"""
AD -> DA
AAD -> ADA -> DAA
ADAD -> DAAD -> DADA -> DDAA

Dを見る→前にあるAは何個？（その分だけ数える）
"""
for i in range(len(s)):
	if s[i] == "A":
		acnt += 1
	elif s[i] == "D":
		ans += acnt
	else:
		acnt = 0
print(ans)

Submission status: Accepted

Solution code:
import sys
import heapq
import math
import fractions
import bisect
import itertools
from collections import Counter
from collections import deque
from operator import itemgetter
def input(): return sys.stdin.readline().strip()
def mp(): return map(int,input().split())
def lmp(): return list(map(int,input().split()))

s=input()
n=len(s)
i=0
k=0
l=[[]]
while i<n:
    if s[i]=="A":
        l[k].append(0)
    elif i<n-1:
        if s[i:i+2]=="BC":
            l[k].append(1)
            i+=1
        else:
            l.append([])
            k+=1
    i+=1
ans=0
for lis in l:
    m=len(lis)
    if m>0:
        n1=[0]*m
        c=0
        for i in range(m):
            if lis[-1-i]==1:
                c+=1
            n1[-1-i]=c
        for i in range(m):
            if lis[i]==0:
                ans+=n1[i]
print(ans)

Submission status: Accepted

Solution code:
import re

S = 'S' + input()
new_s = list(S.replace('BC', 'D'))


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

Submission status: Accepted

Solution code:
def rep(s):
    a,b='',[]
    for i in range(len(s)):
        if s[i]=='C' or s[i]=='B':
            b.append(a)
            a=''
        else:
            a+=s[i]
    b.append(a)
    a=[]
    for i in range(len(b)):
        if b[i]!='':
            a.append(b[i])
    return a
s=rep(input().replace('BC','D'))
b=0
for i in s:
    a=0
    for j in i:
        if j=='A':
            a+=1
        else:
            b+=a
print(b)

Submission status: Accepted

Solution code:
s = input()
i = 0
p = []
tmp =[]
n = len(s)
while i<n-1:
    if(s[i]=="A" or s[i:i+2]=="BC"):
        if s[i]=="A":
            
            tmp.append(1)
            i+=1
        else:
            tmp.append(0)
            i+=2

    else:
        p.append(tmp)
        tmp = []
        i+=1
p.append(tmp)
res = 0
for i in range(len(p)):
    anum = 0
    bcnum = 0
    for j in range(len(p[i])):
        if p[i][j]:anum+=1
        else:
            res += (anum)
print(res)

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

S = list(str(input()))
length = len(S)

abc_cnt = 0
a_cnt = 0
ans = 0
for i in range(length):
    s = S[i]
    if s=='A':
        if abc_cnt!=1:
            a_cnt = 0
        a_cnt += 1
        abc_cnt = 1
    elif s=='B':
        if abc_cnt==1:
            abc_cnt += 1
        else:
            a_cnt = 0
            abc_cnt = 0
    else:
        if abc_cnt==2:
            abc_cnt = 1
            ans += a_cnt
        else:
            a_cnt = 0
            abc_cnt = 0
print(ans)

Submission status: Accepted

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

cnt = 0
ans = []
for i in range(len(s)):
    if s[i] == "A": cnt += 1
    elif s[i] == "D":ans.append(cnt)
    else: cnt = 0
print(sum(ans))

Submission status: Accepted

Solution code:
s=input()
s=s.replace("BC","D")
m=[]
is_seq=False
t=""
for ss in s:
  if is_seq:
    if ss=="A" or ss=="D":
      t+=ss
    else:
      m.append(t)
      t=""
      is_seq=False
  else:
    if ss=="A":
      is_seq=True
      t+=ss
if t!="":
  m.append(t) 
# print(m)
ans=0
for mm in m:
  cnt_a=mm.count("A")
  for i in range(len(mm)):
    if mm[i]=="A":
      ans+=len(mm)-cnt_a-i
      cnt_a-=1
print(ans)

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline

S = readline().rstrip().replace("BC","X")

# AAXXX のようにAとXだけで構成されている部分は、
# Xを全て左に移動する
# BとCが残っている部分で切れる

parts = S.replace("B",",").replace("C",",").split(",")

ans = 0
for part in parts:
  # Xを探し、Xにあったら、そのときのインデックス - それまでにXを見つけた数する
  cnt = 0
  for i in range(len(part)):
    if part[i] == "X":
      ans += (i - cnt)
      cnt += 1

print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache


#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AtoZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)


#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1:
    arr.append([temp, 1])
  if arr==[]:
    arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n:
    return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############

S = S().replace("BC","X")

ans = []
prev = "Z"
for s in S:
  if s in "AX":
    if prev in "AX":
      ans[-1].append(s)
    else:
      ans.append([s])
  prev = s
res = 0
for D in ans:
  n = len(D)
  count = 0
  place = 0
  for i in range(n):
    if D[i] == "A":
      count += 1
      place += i+1
  res += count*(n+(n-count+1))//2 - place
print(res)