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 Scala (2.13.1) (judge verdict: Wrong Answer)

import java.util.Scanner


object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val s = sc.next().toCharArray
    
    val rs = new Array[Int](n)
    val gs = new Array[Int](n)
    val bs = new Array[Int](n)
    
    for (i <- s.indices) {
      if (i > 0) {
        s(i) match {
          case 'R' =>
            rs(i) = rs(i - 1) + 1
            gs(i) = gs(i - 1)
            bs(i) = bs(i - 1)
          case 'G' =>
            rs(i) = rs(i - 1)
            gs(i) = gs(i - 1) + 1
            bs(i) = bs(i - 1)
          case 'B' =>
            rs(i) = rs(i - 1)
            gs(i) = gs(i - 1)
            bs(i) = bs(i - 1) + 1
        }
      } else {
        s(i) match {
          case 'R' =>
            rs(i) = 1
            gs(i) = 0
            bs(i) = 0
          case 'G' =>
            rs(i) = 0
            gs(i) = 1
            bs(i) = 0
          case 'B' =>
            rs(i) = 0
            gs(i) = 0
            bs(i) = 1
        }
      }
    }
    
    var ans = 0L
    
    for (i <- n - 1 to 2 by -1) {
      for (j <- i - 1 to 1 by -1) {
        println(i, j, j - (i - j))
        if ((s(i) == 'R' && s(j) == 'G') || (s(i) == 'G' && s(j) == 'R')) {
          ans += bs(j)
          val m = i - j
          val n = j - m
          if (0 <= n && s(n) == 'B') {
            ans -= 1
          }
        } else if ((s(i) == 'R' && s(j) == 'B') || (s(i) == 'B' && s(j) == 'R')) {
          ans += gs(j)
          val m = i - j
          val n = j - m
          if (0 <= n && s(n) == 'G') {
            ans -= 1
          }
        } else if ((s(i) == 'B' && s(j) == 'G') || (s(i) == 'G' && s(j) == 'B')) {
          ans += rs(j)
          val m = i - j
          val n = j - m
          if (0 <= n && s(n) == 'R') {
            ans -= 1
          }
        }
      }
      
    }
    
    printArray(gs)
    printArray(rs)
    printArray(bs)
    println(ans)
  }
  
  def printArray[T](arr: Array[T]): Unit = {
    for (i <- arr.indices) {
      print(s"${arr(i)} ")
    }
    println()
  }
}