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 Kotlin (1.3.71) (judge verdict: Accepted)



import java.util.*

fun main(args:Array<String>) {
    val sc = Scanner(System.`in`)
    val n = sc.nextInt() // <= 4000
    val s = sc.next()
    var ans = 0L
    val m = mapOf('R' to 0, 'G' to 1, 'B' to 2)

    val acc = IntArray(3){0}
    val counts = Array(3){IntArray(n+1)}

    for(i in s.indices) {
        val idx = m[s[i]]!!
        acc[idx]++
        counts[idx][i] = acc[idx]
    }

    for(i in 0 until 3) {
        var j = 0
        val count = counts[i]
        while (j < n) {
            if(count[j] != 0) {
                val d = count[j]
                ++j
                while (j < n && count[j] == 0) {
                    count[j++] = d
                }
            } else {
                ++j
            }
        }
    }
    // R G B
    for(i in 0 until n) {
        for(j in i + 1 until n) {
            if(s[i] == s[j]) continue
            // 남은 인덱스
            val remain = 3 - (m[s[i]]!! + m[s[j]]!!)
            val diff = j - i

            var v = counts[remain][n - 1] - counts[remain][j]
            if(j + diff < n && counts[remain][j + diff] != counts[remain][j + diff - 1]) {
                --v
            }

            ans += v 

            // k > j && k - j > d
            // total remain size - [k <=d + j

            // k > j && k - j < d
            // lower bound (j + d) - lower bound(j)

            // k - j > d
            // k - j < d
        }
    }
    println(ans)


}