Problem:
Score : 400 points

Problem Statement

We have a string S of length N consisting of R, G, and B.

Find the number of triples (i,~j,~k)~(1 \leq i < j < k \leq N) that satisfy both of the following conditions:

S_i \neq S_j, S_i \neq S_k, and S_j \neq S_k.

j - i \neq k - j.

Constraints

1 \leq N \leq 4000

S is a string of length N consisting of R, G, and B.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of triplets in question.

Sample Input 1

4
RRGB

Sample Output 1

1

Only the triplet (1,~3,~4) satisfies both conditions. The triplet (2,~3,~4) satisfies the first condition but not the second, so it does not count.

Sample Input 2

39
RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB

Sample Output 2

1800

Solution in Haskell (GHC 8.8.3) (judge verdict: Runtime Error)

import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import qualified Data.Vector as V
import Data.List

main = abc162d

abc162d = do
    [n] <- getIntList
    s <- BS.getLine
    let rgbV = convRGB s (V.empty, V.empty, V.empty)
    print $ solveD rgbV

convRGB s (r,g,b)
    | BS.null s = (r,g,b)
    | BS.head s == 'R' = convRGB (BS.tail s) (V.cons n r,g,b)
    | BS.head s == 'G' = convRGB (BS.tail s) (r,V.cons n g,b)
    | BS.head s == 'B' = convRGB (BS.tail s) (r,g,V.cons n b)
    where n = V.length r + V.length g + V.length b + 1

solveD (r,g,b)
    | V.length r == 1 = subSolveD (V.head r, g, b)
    | otherwise = subSolveD (V.head r, g, b) + solveD (V.tail r, g, b)

subSolveD (r,g,b)
    | V.length g == 1 = subSubSolveD (r, V.head g, b)
    | otherwise = subSubSolveD (r, V.head g, b) + subSolveD (r, V.tail g, b)

subSubSolveD :: (Int, Int, V.Vector Int) -> Int
subSubSolveD (r,g,b)
    | g < r
        = V.length b - (if bgrBool then 1 else 0) - (if grbBool then 1 else 0) - (if xbxBool then 1 else 0)
    | r < g
        = V.length b - (if brgBool then 1 else 0) - (if rgbBool then 1 else 0) - (if xbxBool then 1 else 0)
    where bgrBool = V.elem (g - (r - g)) b
          grbBool = V.elem (r + (r - g)) b
          brgBool = V.elem (r - (g - r)) b
          rgbBool = V.elem (g + (g - r)) b
          xbxBool = even (r + g) && V.elem (div (r + g) 2) b

readInt = fst . fromJust . BS.readInteger
readIntList = map readInt . BS.words
getIntList = readIntList <$> BS.getLine