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

Solution in Haskell (GHC 7.10.3) (judge verdict: Accepted)

-- https://github.com/minoki/my-atcoder-solutions
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.ByteString.Char8 as BS

countBCs :: BS.ByteString -> (Int, BS.ByteString)
countBCs s = loop 0 s
  where
    loop !i s | "BC" `BS.isPrefixOf` s = loop (i+1) (BS.drop 2 s)
              | otherwise = (i, s)

parse :: BS.ByteString -> [[(Int, Int)]]
parse s = doParse [] s
  where
    doParse acc s = case BS.uncons s of
      Nothing -> [reverse acc]
      Just ('A', xs) -> let (as, xs') = BS.span (== 'A') xs
                            (bcs, xs'') = countBCs xs'
                        in if bcs == 0
                           then reverse acc : doParse [] xs''
                           else doParse ((BS.length as + 1, bcs) : acc) xs''
      Just (_, xs) -> reverse acc : doParse [] xs

calc :: [(Int, Int)] -> Int
calc xs = loop 0 0 xs
  where
    loop :: Int -> Int -> [(Int,Int)] -> Int
    loop !s !sa [] = s
    loop !s !sa ((a,b):xs) = loop (s + (sa + a) * b) (sa + a) xs

main = do
  s <- BS.getLine
  print $ sum $ map calc $ parse s