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: Time Limit Exceeded

Solution code:
s = list(input())
length = len(s)
test = False
count = 0


def check():
    for i in range(length - 2):
        if s[i] == "A" and s[i + 1] == "B" and s[i + 2] == "C":
            return False
        else:
            pass
    return True


def change():
    for i in range(length - 2):
        if s[i] == chr(65) and s[i+1] == chr(66) and s[i+2] == chr(67):
            s[i] = 'B'
            s[i+1] = 'C'
            s[i+2] = 'A'
            global count
            count += 1

    return count


while not test:
    if len(s) < 3:
        count = 0
        break
    test = check()
    change()

print(count)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python

import sys
import re

s= sys.stdin.readline().strip()
n= len(s)
#
c= 0
p1= re.compile("ABC")
p2= re.compile("A+$")
p3= re.compile("^(BC)+")
#
while True:
    m =p1.search( s )
    if not m: break
    i= m.start() + 1
    a=0
    for ch in reversed(s[:i]):
        if ch=="A": a+=1
        else: break
    #
    bc= 1
    j= i+2
    while True:
        k= j+2
        if k>n or s[j:k]!="BC": break
        j += 2
        bc+= 1

    s= ("A"*a) + s[i+2*bc:]
    c+= a*bc

print( c )

Submission status: Time Limit Exceeded

Solution code:
# coding: UTF-8
# sample code

import re

s = input()

num = 0
i = 0
t = s
while True:
	l = len(re.findall('ABC', t))
	if l == 0:
		break
	num += l
	u = t.replace('ABC', 'BCA')
	t = u
	i += 1

print(num)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
s = input()
count = 0
while s.find("ABC") != -1:
    s = s.replace("ABC", "BCA", 1)
    count += 1
print(count)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 20:47:47 2019

@author: Owner
"""

# -*- coding: utf-8 -*-
"""
Created on Sat Apr 13 09:53:12 2019

@author: Owner
"""
import 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()
def main(): 
    S = collections.deque(s)
    res = 0
    idx = "".join(list(S)).find("ABC")
    while idx != -1:
        cnt = 0
        res+=1
        for i in range(idx):
            if S[idx-(i+1)] == "A":
                res+=1
                cnt+=1
            else:
                break
        for i in range(idx+3):
            S.popleft()
        for i in range(cnt+1):
            S.appendleft("A")
        #print("".join(list(S)), "".join(list(S)).find("ABC"))            
        idx = "".join(list(S)).find("ABC")
        
    
    
    
    
    print(res)
                
                
                
            
            
                

    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
S=input()
count=0
for i in range(2,len(S)-1):
    if S[i-2:i+1]=="ABC":
        count_A=1
        j=i-2
        while S[j]=="A" and j-1>=0:
            j=j-1
            if S[j]=="A":
                count_A+=1
        count+=count_A
        S=S[0:i-count_A-1]+"BC"+"A"*count_A+S[i+1:len(S)]
i=len(S)-1
if S[i-2:i+1]=="ABC":
        count_A=1
        j=i-2
        while S[j]=="A" and j-1>=0:
            j=j-1
            if S[j]=="A":
                count_A+=1
        count+=count_A
print(count)

Submission status: Time Limit Exceeded

Solution code:
# coding: UTF-8
# sample code

import re

s = input()

num = 0
i = 0
t = [ s ]
while True:
	l = len(re.findall('ABC', t[i]))
	if l == 0:
		break
	num += l
	u = t[i].replace('ABC', 'BCA')
	t.append(u)
	i += 1

print(num)

Submission status: Time Limit Exceeded

Solution code:
S=list(input())

def repABC(S,ans):
    S1=S[:]
    S2 =S[:]
    S2.pop(0)
    S3 =S2[:]
    S3.pop(0)
    for i in range(len(S3)):
        if S1[i]=="A" and S2[i]=="B" and S3[i]=="C":
            S[i]="B"
            S[i+1]="C"
            S[i+2]="A"
            ans=ans+1
    return S,ans

ans=0
for i in range(10000000000):
    if len(S)<2:
        break
        
    flag=ans
    S,ans=repABC(S,ans)
    if flag==ans:
        break
        
print(ans)

Submission status: Time Limit Exceeded

Solution code:
s = input()
cnt = 0
while "ABC" in s:
    s = s.replace("ABC", "BCA", 1)
    cnt += 1
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
import sys

S=input()
if len(S)<2: print(0),sys.exit()
elif len(S)==3:
    print(1 if S=="ABC" else 0)
    sys.exit()

s=[]
a=[]
x=ord("A")
l=len(S)
for i in range(l-2):
    s.append(ord(S[i])-x)
    if S[i:i+3]=="ABC": a.append(i)
s.append(ord(S[l-2])-x)
s.append(ord(S[l-1])-x)
s.append
a=[a[i] for i in range(len(a)-1,-1,-1)]


tmp=0
abc,bca=[0,1,2],[1,2,0]
ans=0
while True:
    if a==[] or a[-1]>=len(s)-2: break
    tmp=a[-1]
    if s[tmp]==0 and s[tmp+1]==1 and s[tmp+2]==2:
        s[tmp],s[tmp+1],s[tmp+2]=1,2,0
        a.append(tmp+2)
        if tmp>0 and s[tmp-1]==0: a.append(tmp-1)
        ans+=1
    else: a.pop(-1)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 20 20:47:47 2019

@author: Owner
"""

# -*- coding: utf-8 -*-
"""
Created on Sat Apr 13 09:53:12 2019

@author: Owner
"""
import numpy as np
import sys
import collections
import scipy.misc
import math
from operator import itemgetter
import itertools
import copy
import bisect

#素因数を並べる
def prime_decomposition(n):
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n /= i
      table.append(int(i))
    i += 1
  if n > 1:
    table.append(int(n))
  return table   
# 桁数を吐く
def digit(i):
    if i > 0:
        return digit(i//10) + [i%10]
    else:
        return []
    
def getNearestValueIndex(list, num):
    """
    概要: リストからある値に最も近い値のインデックスを取得する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return idx

def find_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default

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()
def main(): 
    S = collections.deque(s)
    res = 0
    idx = "".join(list(S)).find("ABC")
    while idx != -1:
        cnt = 0
        res+=1
        for i in range(idx):
            if S[idx-(i+1)] == "A":
                res+=1
                cnt+=1
            else:
                break
        for i in range(idx+3):
            S.popleft()
        for i in range(cnt+1):
            S.appendleft("A")
        #print("".join(list(S)), "".join(list(S)).find("ABC"))            
        idx = "".join(list(S)).find("ABC")
        
    
    
    
    
    print(res)
                
                
                
            
            
                

    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
''' 
------------------------
author : iiou16
------------------------
'''

def main():
    S = input()

    count_num = 0
    while "ABC" in S:
        # print(S)
        count_num += S.count("ABC")
        S = S.replace("ABC", "BCA")
        # print("rep", S)
    print(count_num)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
s = input()

ans = 0

while "ABC" in s:
    cnt = s.count("ABC")
    s = s.replace("ABC","BCA",cnt)
    ans += cnt
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import re
S = input()
N1 = re.subn('A','0',S)
N2 = re.subn('BC','1',N1[0])
S_li = N2[0].split('B')

count = 0
for bigstr in S_li:
    if len(bigstr):
        li = bigstr.split('C')
        for l in li:
            if len(l):
                while True:
                    a = l.find('0')
                    bc = l.rfind('1')
                    if a<0 or bc<0:
                        break
                    if a < bc:
                        l = l[a+1:bc]
                        count += (bc-a)
                    else:
                        break

print(str(count))

Submission status: Time Limit Exceeded

Solution code:
def li():
    return list(map(int, input().split()))


if __name__ == "__main__":
    s = input()
    ope_num = 0
    index = 0
    a_stock = 0
    b_stock = 0
    s = list(s)
    while index < len(s):
        # print(s)
        # print(index)
        # print(ope_num)
        # print()
        si = s[index]
        if si == "A":
            if b_stock > 0:
                a_stock = 1
            else:
                a_stock = a_stock + 1
            b_stock = 0
        elif a_stock > 0:
            if b_stock == 0:
                if si == "B":
                    b_stock = 1
                else:
                    a_stock = 0
                    b_stock = 0
            elif si == "C":
                ope_num = ope_num + a_stock
                # s[index - 2 - a_stock + 1] = "B"
                # s[index - 1 - a_stock + 1] = "C"
                for i in range(a_stock - 1, -1, -1):
                    s[index - i] = "A"
                index = index - a_stock
                a_stock = 0
                b_stock = 0
            else:
                a_stock = 0
                b_stock = 0
        else:
            a_stock = 0
            b_stock = 0
        index = index + 1
    print(ope_num)

# ABCの数
# ABCの前にあるAの分だけ追加で操作できる
# ABCの後にある(BC)の分だけ追加で操作できる

# Aがあれば覚えておく
# ABCと来たら、それより前側に隣接しているAの回数だけ追加で操作できる
# 見つかったABCをBCAに置き換える
# BCAのAから走査を継続する

Submission status: Time Limit Exceeded

Solution code:
import sys

sys.setrecursionlimit(10000)
mod = 1000000007


def mul(a, b):
    return ((a % mod) * (b % mod)) % mod


def power(x, y):
    if y == 0:
        return 1
    elif y == 1:
        return x % mod
    elif y % 2 == 0:
        return power(x, y / 2) ** 2 % mod
    else:
        return power(x, y / 2) ** 2 * x % mod


def div(a, b):
    return mul(a, power(b, mod - 2))


# def gcd(a_gcd, b_gcd):
#     while b_gcd != 0:
#         a_gcd, b_gcd = b_gcd, a_gcd % b_gcd
#     return a_gcd
#
#
# def lcm(a_lcm, b_lcm):
#     return a_lcm * b // gcd(a_lcm, b_lcm)
#
#
# def max_sum(N_max_sum, a_max_sum):
#     dp = [0] * (N_max_sum + 1)
#     for i in range(N_max_sum):
#         dp[i + 1] = max(dp[i], dp[i] + a_max_sum[i])
#     return dp[N]
#
#
# def knapsack(N_knapsack, W, weight, value):
#     inf = float("inf")
#     dp = [[-inf for _ in range(W+1)] for j in range(N_knapsack + 1)]
#     for i in range(W+1):
#         dp[0][i] = 0
#
#     for i in range(N_knapsack):
#         for w in range(W+1):
#             if weight[i] <= w:
#                 dp[i+1][w] = max(dp[i][w-weight[i]]+value[i], dp[i][w])
#             else:
#                 dp[i+1][w] = dp[i][w]
#     return dp[N_knapsack][W]
#
#
# class UnionFind:
#     def __init__(self, n):
#         self.par = [i for i in range(n+1)]
#         self.rank = [0] * (n+1)
#
#     # 検索
#     def find(self, 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 = self.find(x)
#         y = self.find(y)
#         if self.rank[x] < self.rank[y]:
#             self.par[x] = y
#         else:
#             self.par[y] = x
#             if self.rank[x] == self.rank[y]:
#                 self.rank[x] += 1
#
#     # 同じ集合に属するか判定
#     def same_check(self, x, y):
#         return self.find(x) == self.find(y)


ans = 0


def solve(S):
    global frag
    fraghh = False
    i = 0
    global ans
    while i < len(S):

        if S[i:i + 3] == "ABC":
            S = S[:i] + "BCA" + S[i + 3:]
            ans += 1
            fraghh = True
            break
        i += 1
    if fraghh:
        return S
    else:
        frag = False
        return S


s = input()
# N = int(input())
# A = list(map(int, input().split()))
# X = [int(input()) for _ in range(N)]
frag = True

while frag:
    s = solve(s)



print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter as D, defaultdict as dd
from math import factorial as ft, ceil as aron
from fractions import gcd as pg 
from bisect import insort as ins, bisect_left as bl, bisect_right as br
import sys

#sys.stdin=open("./testfile1.py","r")
raw_input=sys.stdin.readline

f1=lambda : map(int,raw_input().split())
f2=lambda : map(int,list(raw_input()))
f3=lambda : int(raw_input())
f4=lambda : raw_input().rstrip()
def main():
	st=[]
	s=f4()
	n1=0
	ans=0
	for i in s:
		n1+=1
		st.append(i)
		#print st
		if n1>=3 and st[n1-3:]==['A','B','C']:
			#print 123
			s1=[]
			n2=n1-4
			ans+=1
			st[n1-1]="A"
			while n2>-1 and st[n2]=="A":
				ans+=1
				st[n2+2]="A"
				n2-=1
			st[n2+1],st[n2+2]="B","C"
			#print st,12
	print ans


if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
S=input()
scount=0
i=0
while i < 1:
    if 'ABC' in S:
        scount += S.count('ABC')
        S=S.replace('ABC','BCA')
    else:
        print(scount)
        i=2

Submission status: Time Limit Exceeded

Solution code:
s = input()
res = 0
'''
while 'ABC' in s:
    tmp = s.split('ABC')
    res += len(tmp) - 1
    s = 'BCA'.join(tmp)
print(res)
'''
while True:
    if 'ABCBC' in s:
        res += s.count('ABCBC') * 2
        s = s.replace('ABCBC', 'BCBCA')

    if 'ABCABC' in s:
        res += s.count('ABCABC') * 3
        s = s.replace('ABCABC', 'BCBCAA')

    if 'ABC' in s:
        res += s.count('ABC')
        s = s.replace('ABC', 'BCA')
    
    if 'ABC' not in s:
        break
print(res)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
s = input()

Q = deque([])
for i in range(len(s)-2):
	if s[i:i+3]=='ABC':
		Q.append(i)

cnt = 0
while len(Q)!=0:
	cnt += 1
	q = Q.popleft()
	s = s[:q] + 'BCA' + s[q+3:]
	if s[q-1:q]=='A':
		Q.append(q-1)
	if s[q+3:q+5]=='BC':
		Q.append(q+2)
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
import re
exp = "(A+)(BC)+"
res = 0
tmp_end = 0
tmp_A = 0
for m in re.finditer(exp, input()):
  A_len = len(m.group(1)) 
  if tmp_end == m.start(0):
    A_len += tmp_A
  match_str = m.group(0)
  trans_num = A_len * (len(m.group(0)) - len(m.group(1))) / 2
  res += int(trans_num)
  tmp_end = m.end(0)
  tmp_A = A_len
print(res)

Submission status: Time Limit Exceeded

Solution code:
s = input()
ans = 0
ss = s
a = 1
for i in range(len(s)):
    a = s[max(0, a - 1):].find("ABC")
    if a >= 0:
        ans += 1
        s = s[:a] + s[a:].replace("ABC", "BCA", 1)
    if a == -1:
        break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
inputStr = str(input())
i = 0
while('ABC' in inputStr):
    inputStr = inputStr.replace('ABC','BCA' ,1)
    # print(inputStr)
    i = i + 1
print(i)

Submission status: Time Limit Exceeded

Solution code:
# coding: UTF-8
# sample code

import re

s = input()

num = 0
i = 0
t = [ s ]
while len(re.findall('ABC', t[i])) != 0:
	num += len(re.findall('ABC', t[i]))
	u = t[i].replace('ABC', 'BCA')
	t.append(u)
	i += 1

print(num)

Submission status: Time Limit Exceeded

Solution code:
li = list(input())
count = 0

i = 0
while(i<len(li)-2):
  if(li[i]=='A' and li[i+1]=='B' and li[i+2]=='C'):
    count += 1
    li[i]='B'
    li[i+1]='C'
    li[i+2]='A'
    if(i!=0 and li[i-1]=='A'):
      i = i-1
    else:
      i = i+2
  else:
    i = i+1

print(count)

Submission status: Time Limit Exceeded

Solution code:
S=list(input())
l = len(S)
i = 0
j = -1
ans = 0
while i<l:
    s = S[i]
    if j>=0:
        if s=="A":
            i+=1
        elif i+1<l and s == "B" and S[i+1] == "C":
            S[i] = "A"
            S[i+1] = "A"
            S[j] = "B"
            S[j+1] = "C"
            ans += i-j
            i = j
            j = -1
        else:
            j = -1
            i += 1
    elif s == "A":
        j=i
        i+=1
    else:
        i+=1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import*
import math
from collections import*
from heapq import*
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf = float("inf")
mod = 10**9+7
from functools import reduce
import sys
sys.setrecursionlimit(10**7)

s = list(input())
n = len(s)
c = n-1
ans = 0
while True:
    if c <2:
        break
    if s[c-2]+s[c-1]+s[c]=="ABC":
        ans += 1
        s[c-2]="B"
        s[c-1]="C"
        s[c]="A"
        if c+2 < n:
            c +=2
    else:
        c -=1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
S=list(input())
n=len(S)
N=n
for xx in range(N):
    if xx<n-1:
        if S[xx]=='B':
            if S[xx+1]=='C':
                S[xx]='D'
                S.pop(xx+1)
                n=n-1
    if xx>n-2:
        break
c=0
n=len(S)
for x in range(n-1):
    if S[x]=='A':
        if S[x+1]=='D':
            S[x]='D'
            S[x+1]='A'
            c=c+1
            if x>0:
                y=x-1
                while S[y]=='A':
                    S[y]='D'
                    S[y+1]='A'
                    c=c+1
                    if y>0:
                        y=y-1
print(c)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
s = input()

Q = deque([])
for i in range(len(s)-2):
	if s[i:i+3]=='ABC':
		Q.append(i)

cnt = 0
while len(Q)!=0:
	cnt += 1
	q = Q.popleft()
	s = s[:q] + 'BCA' + s[q+3:]
	if s[q-1:q]=='A':
		Q.append(q-1)
	if s[q+3:q+5]=='BC':
		Q.append(q+2)

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
s=input()
cnt=0

while "ABC" in s:
    s=s.replace("ABC","BCA",1)
    cnt+=1

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
def li():
    return list(map(int, input().split()))


if __name__ == "__main__":
    s = input()
    ope_num = 0
    index = 0
    a_stock = 0
    b_stock = 0
    s = list(s)
    while index < len(s):
        # print(s)
        # print(index)
        # print(ope_num)
        # print()
        si = s[index]
        if si == "A":
            if b_stock > 0:
                a_stock = 1
            else:
                a_stock = a_stock + 1
            b_stock = 0
        elif a_stock > 0:
            if b_stock == 0 and si == "B":
                b_stock = 1
            elif b_stock > 0 and si == "C":
                ope_num = ope_num + a_stock
                # s[index - 2 - a_stock + 1] = "B"
                # s[index - 1 - a_stock + 1] = "C"
                for i in range(a_stock - 1, -1, -1):
                    s[index - i] = "A"
                index = index - a_stock
                a_stock = 0
                b_stock = 0
            else:
                a_stock = 0
                b_stock = 0
        else:
            a_stock = 0
            b_stock = 0
        index = index + 1
    print(ope_num)

# ABCの数
# ABCの前にあるAの分だけ追加で操作できる
# ABCの後にある(BC)の分だけ追加で操作できる

# Aがあれば覚えておく
# ABCと来たら、それより前側に隣接しているAの回数だけ追加で操作できる
# 見つかったABCをBCAに置き換える
# BCAのAから走査を継続する

Submission status: Time Limit Exceeded

Solution code:
s = str(input())

s = s.replace('BC', 'D').replace('B', 'C').replace('AC', 'C')
sl = s.split('C')
sl = [x for x in sl if x]

c = 0
for l in sl:
    l = list(l)
    ind = [i for i, x in enumerate(l) if x == 'D']
    for i in ind:
        c += l[:i].count('A')
        
print(c)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
def Find_and_Replace(S,f_i):
    i = 2
    count = 0
    while i < len(S):
        if S[i] == 'C':
            if S[i-2] == 'A' and S[i-1] == 'B':
                S[i-2] = 'B'
                S[i-1] = 'C'
                S[i] = 'A'
                count += 1
                f_i = max(2,i-2)
                i += 2
            else:
                i += 3
                f_i = i

        else:
            if S[i] == 'B':
                i += 1
            elif S[i] == 'A':
                i += 2
            else:
                i += 3
    return count,f_i

S = list(input())
total_count = 0
f_i = 2
while True:
    count,new_f_i = Find_and_Replace(S,f_i)
    f_i = new_f_i
    if count <= 0:
        break
    else:
        total_count += count

print(total_count)

Submission status: Time Limit Exceeded

Solution code:
s = input()
res = s.count('ABC')

for i in range(len(s)):
  s = s.replace('ABC', 'BCA')
  res += s.count('ABC')
  if not 'ABC' in s:
    break
  
  
print(res)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python

import sys
import re

s= sys.stdin.readline().strip()
#
c= 0
p1= re.compile("ABC")
p2= re.compile("A+$")
p3= re.compile("^(BC)+")
#
while True:
    m =p1.search( s )
    if not m: break
    i= m.start() + 1
    a = len( p2.search(s[:i]).group())
    bc= len( p3.search(s[i:]).group()) // 2
    s= ("A"*a) + s[i+2*bc:]
    c+= a*bc

print( c )

Submission status: Time Limit Exceeded

Solution code:
s = input()

ans = 0

while "ABC" in s:
    s = s.replace("ABC","BCA",1)
    ans += 1
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
s=input()


i=0
c=0
flag=0
while True:
	if i>len(s)-2: break
	if s[i]=="A":
		flag+=1
		i+=1
	elif flag and s[i:i+2]=="BC":
		s=s[:i-flag]+"BC"+"A"*flag+s[i+2:]
		c+=flag
		i+=2
	else:
		flag=0
		i+=1

print(c)

Submission status: Time Limit Exceeded

Solution code:
s = input()
count = 0
while 'ABC' in s:
        count += s.count('ABC')
        s = s.replace('ABC',"BCA")
print(count)

Submission status: Time Limit Exceeded

Solution code:
import re
from operator import itemgetter

s = input()
cnt = 0
re_subn = re.subn
f = itemgetter(0)
g = itemgetter(1)

for i in range(100000000):
    temp = re_subn("ABC", "BCA", s)
    if s != f(temp):
        s = f(temp)
        cnt += g(temp)
    else:
        break
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
s=input()

cnt=0
while(True):
  if s.find("ABC") == -1:
    break
  else:
    cnt += s.count("ABC")
    s = s.replace("ABC","BCA")
    
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
S=list(input())

def repABC(S,ans,A_position):
    S1=S[:]
    S2 =S[:]
    S2.pop(0)
    S3 =S2[:]
    S3.pop(0)
    
    
    for i in A_position:
        if S1[i]=="A" and S2[i]=="B" and S3[i]=="C":
            S[i]="B"
            S[i+1]="C"
            S[i+2]="A"
            ans=ans+1
            
    return S,ans

ans=0
for i in range(10000000000):
    if len(S)<2:
        break
        
    flag=ans
    A_position=[i for i, x in enumerate(S) if x == "A" and i <len(S)-2]
    S,ans=repABC(S,ans,A_position)
    if flag==ans:
        break
        
print(ans)

Submission status: Time Limit Exceeded

Solution code:
s = input()
res = s.count('ABC')

for i in range(len(s)):
  s = s.replace('ABC', 'BCA')
  res += s.count('ABC')
  
  
print(res)

Submission status: Time Limit Exceeded

Solution code:
s = input()
ss = [ si for si in s ]

cnt = 0
cnti = 0
cntj = 0
i = 0
while True:
    while True:
        if i < len(s)-2 and ss[i] == "A" and ss[i+1] == "B" and ss[i+2] == "C":
            ss[i], ss[i+1], ss[i+2] = "B", "C", "A"
            cnt += 1
            i += 1
            cnti = 0
            if i < len(s)-2-cntj:
                break
        elif i >= len(s)-2-cntj:
            cnti += 1
            cntj += 1
            i = cntj*2
            break
        i += 1
    if cnti > 2:
        break
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
import sys

S=input()
if len(S)<2: print(0),sys.exit()
elif len(S)==3:
    print(1 if S=="ABC" else 0)
    sys.exit()

s=[]
a=[]
x=ord("A")
l=len(S)
for i in range(l-2):
    s.append(ord(S[i])-x)
    if S[i:i+3]=="ABC": a.append(i)
s.append(ord(S[l-2])-x)
s.append(ord(S[l-1])-x)
s.append
a=[a[i] for i in range(len(a)-1,-1,-1)]


tmp=0
abc,bca=[0,1,2],[1,2,0]
ans=0
while True:
    if a==[] or a[-1]>=len(s)-2: break
    tmp=a[-1]
    if s[tmp:tmp+3]==abc:
        s[tmp:tmp+3]=bca
        a.append(tmp+2)
        if tmp>0: a.append(tmp-1)
        ans+=1
    else: a.pop(-1)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
s = list(input())
l = len(s)
pattern = ["A", "B", "C"]
pattern2 = ["B", "C"]

result = 0

q = []
def swapABC(n):
  global result
  if n > 0 and s[n-1] == "A":
    q.append(n-1)
  if n < l-1 and s[n+3 : n+5] == pattern2:
    q.append(n + 2)
  
  s[n], s[n+1], s[n+2] = "B", "C", "A"
  result += 1

for i in range(l-2):
  if s[i:i+3] == pattern:
    swapABC(i)

  while(1):
    if len(q) == 0:
      break
    n = q.pop()
    swapABC(n) 

print(result)

Submission status: Time Limit Exceeded

Solution code:
S = input()

flag = 0
ans = 0
i = 0
S= list(S)


while flag == 0:
    if len(S) < 3+i:
        flag = 1
    elif S[i]=="A" and S[i+1]=="B" and S[i+2]=="C":
        S[i] = 'B'
        S[i+1] = 'C'
        S[i+2] = 'A'
        i=0
        ans+=1
    elif S[i]=="A":
        i+=1
    else:
        S.pop(0)
        i=0

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
''' 
------------------------
author : iiou16
------------------------
'''

def main():
    S = input()

    count = 0
    while "ABC" in S:
        # print(S)
        S = S.replace("ABC", "BCA", 1)
        count += 1
        # print("rep", S)
    print(count)

if __name__ == '__main__':
    main()