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



Sample input:
4
RRGB


Sample output:
1

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N = int(readline())
S = str(sys.stdin.readline().rstrip())

R,G,B = 0,0,0

for c in S:
    if c == 'R':
        R+=1
    elif c == 'G':
        G+=1
    else:
        B+=1

ans = R*G*B

for j in range(N):
    for i in range(N):
        if j-i < 0 or j+i >= N:
            break
        elif S[j-i] != S[j] and S[j+i] != S[j] and S[j+i] != S[j-i]:
            ans-=1

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = input()

R = S.count('R')
G = S.count('G')
B = S.count('B')

A = 0
if R == 0 or G == 0 or B == 0 :
    print(A)
else:
    A = R*G*B
    for i in range((N-3)//2 +1):#間の大きさ
        for j in range(N-3-2*i +1):#スタートからずれていく
            if S[j] != S[j+i+1] and S[j+i+1] != S[j+2*i+2] and S[j+2*i+2] != S[j]:
                A -= 1
    print(A)

Submission status: Accepted

Solution code:
n = int(input())
s = list(input())

ans = s.count('R') * s.count('G') * s.count('B')

for i in range(n):
    for j in range(i + 1, n):
        k = 2 * j - i

        if k >= n:
            continue

        if s[i] != s[j] and s[j] != s[k] and s[k] != s[i]:
            ans -= 1

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = list(input())

ans = s.count('R') * s.count('G') * s.count('B')

for i in range(n):
    for j in range(i + 1, n):
        k = 2 * j - i

        if k >= n:
            continue

        if s[i] != s[j] and s[j] != s[k] and s[k] != s[i]:
            ans -= 1

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S= input()
sub = 0
R,G,B = [],[],[]
r = S.count('R')
g = S.count('G')
b = S.count('B') 
for i in range(N):
    for j in range(i+1,N):
        if 2*j-i > N-1:
            break
        if S[i] != S[j] and S[2*j-i] != S[i] and S[2*j-i] != S[j]:
            sub += 1
ans = r*g*b -sub
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = list(input())

r, g, b = 0, 0, 0

for i in list(s):
    if i == 'R':
        r += 1
    elif i == 'G':
        g += 1
    else:
        b += 1

ans = r * g * b

for i in range(n):
    for j in range(i + 1, n):
        k = 2 * j - i

        if k >= n:
            continue

        if s[i] != s[j] and s[j] != s[k] and s[k] != s[i]:
            ans -= 1

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
count = [0, 0, 0]

for s in S:
    if s == 'R': count[0] += 1
    elif s == 'G': count[1] += 1
    else: count[2] += 1

ans = count[0] * count[1] * count[2]

for j in range(N):
    for i in range(j):
        k = j + j-i
        
        if k < N:
            if S[i] == S[j]: continue
            if S[i] == S[k]: continue
            if S[k] == S[j]: continue
            ans -= 1
            
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
import collections
import copy
import heapq
from collections import defaultdict
from heapq import heappop, heappush
import itertools
input = sys.stdin.readline
from collections import defaultdict
from heapq import heappop, heappush

from decimal import *

##### リストの 二分木検索 #####
# bisect_left(lists, 3)
# bisect_right(lists, 3)

##### プライオリティキュー #####
# heapq.heapify(a) #リストaのheap化
# heapq.heappush(a,x) #heap化されたリストaに要素xを追加
# heapq.heappop(a) #heap化されたリストaから最小値を削除＆その最小値を出力

# heapq.heappush(a, -x) #最大値を取り出す時は、pushする時にマイナスにして入れよう
# heapq.heappop(a) * (-1) #取り出す時は、-1を掛けて取り出すこと

##### タプルリストのソート #####
# sorted(ans) #(a, b) -> 1st : aの昇順, 2nd : bの昇順
# sorted(SP, key=lambda x:(x[0],-x[1])) #(a, b) -> 1st : aの昇順, 2nd : bの降順
# sorted(SP, key=lambda x:(-x[0],x[1])) #(a, b) -> 1st : aの降順, 2nd : bの昇順
# sorted(SP, key=lambda x:(-x[0],-x[1])) #(a, b) -> 1st : aの降順, 2nd : bの降順

# sorted(SP, key=lambda x:(x[1])) #(a, b) -> 1st : bの昇順
# sorted(SP, key=lambda x:(-x[1])) #(a, b) -> 1st : bの降順

##### 累乗 #####
# pow(x, y, z) -> x**y % z

##### 割り算の切り上げ #####
# tmp = -(-4 // 3)

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))

inf = float('inf')
mod = 1000000007

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

def main():
	N = inputInt()
	S = input()
	S = S[:-1]

	R = []
	G = []
	B = []

	for i,val in enumerate(S):
		if val == "R":
			R.append(i)
		elif val == "G":
			G.append(i)
		else:
			B.append(i)

	maxs = len(R) * len(G) * len(B)

	tmp = 0
	for i in range(N):
		for skip in range(0, -(-N // 2)):
			if i+skip+skip >= len(S):
				break
			I = S[i]
			J = S[i+skip]
			K = S[i+skip+skip]

			if I != J and I != K and J != K:
				tmp += 1

	print(maxs-tmp)
	#print(tmp)

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
# nCr mod m
# rがn/2に近いと非常に重くなる
def combination(n, r, mod=10**9+7):
    r = min(r, n-r)
    res = 1
    for i in range(r):
        res = res * (n - i) * modinv(i+1, mod) % mod
    return res

# mを法とするaの乗法的逆元
def modinv(a, mod=10**9+7):
    return pow(a, mod-2, mod)

def egcd(a, b):
    if a == 0:
        return b, 0, 1
    else:
        g, y, x = egcd(b % a, a)
        return g, x - (b // a) * y, y

# nHr mod m
# 問題によって、combination()を切り替えること
def H(n, r, mod=10**9+7):
	# comb = Combination(n+r-1, mod)
	# return comb(n+r-1, r)
    return combination(n+r-1, r, mod)

class Combination:
    """
    O(n)の前計算を1回行うことで，O(1)でnCr mod mを求められる
    n_max = 10**6のとき前処理は約950ms (PyPyなら約340ms, 10**7で約1800ms)
    使用例：
    comb = Combination(1000000)
    print(comb(5, 3))  # 10
    """
    def __init__(self, n_max, mod=10**9+7):
        self.mod = mod
        self.modinv = self.make_modinv_list(n_max)
        self.fac, self.facinv = self.make_factorial_list(n_max)

    def __call__(self, n, r):
        return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod

    def make_factorial_list(self, n):
        # 階乗のリストと階乗のmod逆元のリストを返す O(n)
        # self.make_modinv_list()が先に実行されている必要がある
        fac = [1]
        facinv = [1]
        for i in range(1, n+1):
            fac.append(fac[i-1] * i % self.mod)
            facinv.append(facinv[i-1] * self.modinv[i] % self.mod)
        return fac, facinv

    def make_modinv_list(self, n):
        # 0からnまでのmod逆元のリストを返す O(n)
        modinv = [0] * (n+1)
        modinv[1] = 1
        for i in range(2, n+1):
            modinv[i] = self.mod - self.mod//i * modinv[self.mod%i] % self.mod
        return modinv

if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
N = int(input())
S = input()

if N == 1 or N == 2:
    ans = 0
else:
    R = S.count('R')
    G = S.count('G')
    B = S.count('B')
    rgb = R * G * B

    count = 0
    for i in range(N - 2):
        for j in range(i + 1, N - 1):
            k = 2 * j - i
            if k >= N:
                break 
            if S[i] != S[j] and S[j] != S[k] and S[k] != S[i]:
                count += 1
    ans = rgb - count

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
if n < 3:
  print(0)
else:
  s = str(input())
  r = 0
  g = 0
  b = 0
  for i in s:
    if i == "R":
      r += 1
    if i == "G":
      g += 1
    if i == "B":
      b += 1
  ans = r*g*b
  for i in range(n-2):
    for j in range(i+1,n-1):
      if 2*j-i > n-1:
        break
      if s[i] != s[j] and s[j] != s[2*j-i] and s[i] != s[2*j-i]:
        ans -= 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = input()

r = 0
g = 0
b = 0
for i in range(n):
    if s[i] == "R":
        r += 1
    elif s[i] == "G":
        g += 1
    else:
        b += 1

ans = r * g * b

for i in range(1, (n-1)//2+1):
    for j in range(0, n-i*2):
        x = j
        y = j + i
        z = j + i * 2
        if s[x]!=s[y] and s[y]!=s[z] and s[z]!=s[x]:
            ans -= 1

print(ans)

Submission status: Accepted

Solution code:
N = int(input()) #<=4000
S = list(input())

R_index = list()
G_index = list()
B_index = list()

for i in range(N):
    if S[i] == "R":
        R_index.append(i+1)
    elif S[i] == "G":
        G_index.append(i+1)
    if S[i] == "B":
        B_index.append(i+1)

#組 (i, j, k) (1≤i<j<k≤N) の数を求めてください。
#Si≠Sj かつ Si≠Sk かつ Sj≠Sk である
#j−i≠k−jの条件下で組み合わせる
#j−i=k−j
#↓
#2j−i=k ≡ 2j−k=i  ≡ (i+k)/2 = j はNGということ。

ans = len(R_index)*len(G_index)*len(B_index) #まず全通りを計算
B_set = set(B_index)

#NG分を除去する
for R in R_index:
    for G in G_index:
        #R,G,Bのi,j,kへのあてはめ方は6通り。大小関係にも注意
        #(R,G,B),(R,B,G),(G,B,R),(G,R,B),(B,R,G),(B,G,R)
        if (R+G)/2 in B_set:
            ans -= 1
        if 2*G-R in B_set:
            ans -= 1
        if  2*R-G in B_set:
            ans -= 1
        
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = input()

a = [0] * n
for i in range(n):
    if s[i] == 'R': a[i] = 0
    if s[i] == 'G': a[i] = 1
    if s[i] == 'B': a[i] = 2

cnt = [0] * 3
for i in range(n):
    cnt[a[i]] += 1
    
ans = 1
for i in range(3):
    ans *= cnt[i]

#1 <= i <= j <= k <= n
for j in range(n):
    for i in range(j):
        k = j + (j - i)
        if k < n:
            if a[i] == a[j]: continue
            if a[i] == a[k]: continue
            if a[k] == a[j]: continue
            ans -= 1
            
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
R = S.count('R')
G = S.count('G')
B = S.count('B')
ans = R*G*B
for i in range(N):
    for d in range(N):
        j = i + d
        k = i + 2*d
        if k >= N:
            break
        if S[i] != S[j] and S[i] != S[k] and S[j] != S[k]:
            ans -= 1
print(ans)

Submission status: Accepted

Solution code:
from numba import njit
import numpy as np
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N = int(readline())
S = np.array(list(readline().rstrip()), np.int8)

R = np.sum(S == ord('R'))
B = np.sum(S == ord('B'))
G = np.sum(S == ord('G'))


@njit
def f(S):
    N = len(S)
    ret = 0
    for i in range(N):
        for j in range(i + 1, N):
            k = j + j - i
            if k >= N:
                break
            if S[i] != S[j] and S[i] != S[k] and S[j] != S[k]:
                ret += 1
    return ret


answer = R * B * G - f(S)
print(answer)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
import numpy as np
from numba import njit

MOD = 10**9 + 7

N = int(readline())
S = np.array(list(read().rstrip()), np.int8)

R = np.sum(S == ord('R'))
B = np.sum(S == ord('B'))
G = np.sum(S == ord('G'))

@njit
def f(S):
    N = len(S)
    ret = 0
    for i in range(N):
        for j in range(i + 1, N):
            k = j + j - i
            if k >= N:
                break
            if S[i] != S[j] and S[i] != S[k] and S[j] != S[k]:
                ret += 1
    return ret

answer = R * B * G - f(S)
print(answer)

Submission status: Accepted

Solution code:
n = int(input())
s = input()

r = g = b = 0
for i in range(n):
    if s[i] == 'R':
        r += 1
    elif s[i] == 'G':
        g += 1
    else:
        b += 1

x = 0
for i in range(n):
    for j in range(i+1, n):
        k = j + j - i
        if k < n and s[i] != s[j] and s[j] != s[k] and s[k] != s[i]:
            x += 1
print(r*g*b-x)

Submission status: Accepted

Solution code:
import copy
import collections
def f(s):
    h = {('R','G'): 'B', ('B','G'): 'R', ('R','B'): 'G',('R','G')[::-1]: 'B', ('B','G')[::-1]: 'R', ('R','B')[::-1]: 'G', }
    c = collections.Counter()
    cc = [None] * (len(s)+1)
    cc[-1] = copy.deepcopy(c)
    for jj in range(len(s)-1,-1,-1):
        c[s[jj]]+=1
        cc[jj] = copy.deepcopy(c)


    res = 0
    for i in range(len(s)):
        for j in range(i + 1, len(s)):
            if s[j] != s[i]:
                res += cc[j+1][h[(s[i],s[j])]] 
                
                k = j + (j - i)
                if k < len(s) and s[k] == h[(s[i],s[j])]:
                    res -=1
    return res
raw_input()
print f(raw_input())

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import collections
n = int(input())
s = list(input())

c = collections.Counter(s)
total = c['R'] * c['G'] * c['B']
tmp = 0
#print(total)
for i in range(1, n - 1):
    for j in range(i + 1, n):
        k = 2 * j - i
        if i <= k <= n:
            #print(i, j, k)
            if s[i-1] != s[j-1] and s[i-1] != s[k-1] and s[j-1] != s[k-1]:
                tmp += 1
print(total - tmp)

Submission status: Accepted

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

import sys
readline = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)

MOD = 10 ** 9 + 7

n = int(readline())
s = list(readline().rstrip())

r = s.count(ord('R'))
g = s.count(ord('G'))
b = s.count(ord('B'))

count = r * g * b
for i in range(n):
    for j in range(1, min(i + 1, n - i)):
        if s[i - j] != s[i] and s[i] != s[i + j] and s[i - j] != s[i + j]:
            count -= 1

print(count)

Submission status: Accepted

Solution code:
n=int(input())
S=list(input())
C=[0]*3
for i in range(n):
  if S[i]=="R":
    C[0]+=1
  elif S[i]=="G":
    C[1]+=1
  else:
    C[2]+=1
b=C[0]*C[1]*C[2]
a=0
for i in range(n-2):
  for j in range(i+1,n-1):
    k=j*2-i
    if k>=n:
      continue
    if S[i]!=S[j] and S[j]!=S[k] and S[k]!=S[i]:
      a=a+1
print(b-a)

Submission status: Accepted

Solution code:
n, s = int(input()), input()
a = ["R", "G", "B"]
cnt = [0, 0, 0]
for i in s:
    cnt[a.index(i)] += 1
c = cnt[0] * cnt[1] * cnt[2]
for i in range(1, n-1):
    for j in range(i+1, n):
        k = 2 * j - i
        if j-1 < k-1 < n:
            if s[i-1] != s[j-1] and s[j-1] != s[k-1] and s[k-1] != s[i-1]:
                c -= 1

print(c)

Submission status: Accepted

Solution code:
#%%code
def resolve():
    N=int(input())
    S=input()
    RGB=[0,0,0]
    subcnt=0
    for i,c in enumerate(S):
        if c=="R":RGB[0]+=1
        if c=="G":RGB[1]+=1
        if c=="B":RGB[2]+=1
            
        for j in range(i+1,N):
            s=S[j]
            k=j*2-i
            if k<N :
                x=S[k]
                if   x!=s and s!=c and x!=c :
                    #print(i,j,k)
                    
                    subcnt+=1
            else:break

    #print(RGB,subcnt)
    A=RGB[0]*RGB[1]*RGB[2]
    print(A-subcnt)
            
#%%submit!
resolve()

Submission status: Accepted

Solution code:
N = int(input())
S = "A"
S += input()
r = 0
g = 0
b = 0
k = 0
for i in range(1, N+1):
    if S[i] == "R":
        r += 1
    elif S[i] == "G":
        g += 1
    else:
        b += 1

sum = r * g * b
for i in range(1, N-1):
    for j in range(i+1,N):
        k = 2*j - i
        if k <= N:
            if S[j] != S[i] and S[k] != S[j] and S[i] != S[k]:
                sum -= 1

print(sum)

Submission status: Accepted

Solution code:
n=int(input())
s=list(input())
ans=s.count('R')*s.count('G')*s.count('B')
for i in range(n):
  if s[i] =="R":
    s[i]=1
  elif s[i] =="G":
    s[i]=2
  elif s[i] =="B":
    s[i]=4
for i in range(n):
  for j in range(i+1,n):

    k=2*j-i
    if k>= n:
      continue
    if s[i]+s[j]+s[k]==7:
      ans -=1
print (ans)

Submission status: Accepted

Solution code:
from math import floor
n=int(input())
s=input()
r=0
g=0
b=0
for i in range (len(s)):
  if s[i]=='R':
    r+=1
  elif s[i]=='B':
    b+=1
  else:
    g+=1
c=0
for i in range(n - 2):
    for k in range(i + 2, n):
        if ( i + k ) % 2 != 0:
            continue
        j = ( i + k ) // 2
        if s[i]!=s[j] and s[j]!=s[k] and s[k]!=s[i]:
            c += 1
 
      
ans=r*g*b-c;
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = list(input())
R = []
G = []
B = []
Rsize =0
Gsize =0
Bsize =0
for i in range(0,N,1):
    if S[i] == "R":
        Rsize+=1
    elif S[i] == "G":
        Gsize+=1
    elif S[i] == "B":
        Bsize+=1
counter = Rsize*Gsize*Bsize
for i in range(0,N-1,1):
    for j in range(i+1,N,1):
        k = 2*j - i
        if k < N:
            if S[i]!=S[j] and S[j]!=S[k] and S[i]!=S[k]:
                counter -=1
print(counter)

Submission status: Accepted

Solution code:
n = int( input() )
s = list( input() )
r = []
g = []
b = []

for i in range(n):
    if s[i] == "R":
        r.append(i)
    elif s[i] == "G":
        g.append(i)
    elif s[i] == "B":
        b.append(i) 

cnt = 0
for i in range(n - 2):
    for k in range(i + 2, n):
        if ( i + k ) % 2 != 0:
            continue
        j = ( i + k ) // 2
        if s[i]!=s[j] and s[j]!=s[k] and s[k]!=s[i]:
            cnt += 1

print( len(r) * len(g) * len(b) - cnt )

Submission status: Accepted

Solution code:
N = int(input())
string = input()
 
result = string.count('R')*string.count('G')*string.count('B')
 
for i in range(N-2):
  for j in range(i+1, N-1):
    k = 2*j-i
    if k>=N:
      break
    if string[i] != string[j] and string[j] != string[k] and string[i] != string[k]:
      result -= 1
print(result)

Submission status: Accepted

Solution code:
N = int(input())
S = input()

U = S.count('R') * S.count('G') * S.count('B')

for i in range(N):
    for j in range(i+1, N):
        k = 2 * j - i
        if k >= N:
            break
        elif S[i] != S[j] and S[j] != S[k] and S[k] != S[i]:
            U -= 1
print(U)

Submission status: Accepted

Solution code:
import collections

N=int(input())
S=input()

lenR=S.count("R")
lenG=S.count("G")
lenB=S.count("B")

count=0
for i in range(N-2):
    for j in range(i,N-1):
        k=2*j-i
        if k>=N:
            continue
        else:
            if (S[i] != S[j]) and (S[i]!=S[k]) and (S[j]!=S[k]):
                count+=1
    
print(lenR*lenG*lenB-count)

Submission status: Accepted

Solution code:
N = int(input())
S = input()

r_num = S.count('R')
g_num = S.count('G')
b_num = S.count('B')

num = r_num * g_num * b_num

for j in range(N):
    for i in range(j):
        k = j + (j - i)
        if k < N:
            if S[i] == S[j]:
                continue
            if S[i] == S[k]:
                continue
            if S[j] == S[k]:
                continue
            num -= 1

print(num)

Submission status: Accepted

Solution code:

N = int(input())
S = input()

r = S.count("R")
g = S.count("G")
b = S.count("B")

all_case = r*g*b

excluded_case = 0
for i in range(N):
    for j in range(i+1, N):
        if S[i] == S[j]: continue
        k = j*2-i
        if k>= N or S[k] == S[i] or S[k] == S[j]: continue
        excluded_case += 1

print(all_case-excluded_case)

Submission status: Accepted

Solution code:
n = int(input())
s = input()

dic = {k: 0 for k in "RGB"}

for i in range(n):
  dic[s[i]] += 1
  
res = dic['R'] * dic['G'] * dic['B']

for i in range(n):
  for j in range(i+1, n):
    k = 2*j - i
    if k >= n: continue
    if s[i]!=s[j] !=s[k] !=s[i]: res -= 1

print(res)

Submission status: Accepted

Solution code:
n,s=open(0)
r,g,b=map(s.count, "RGB");e=enumerate
print(r*g*b-sum(f!=g!=s[i+j]!=f for i,f in e(s)for j,g in e(s[i:-1:2])))

Submission status: Accepted

Solution code:
n, s = open(0)
r, g, b = map(s.count, "RGB")
e = enumerate
print(r*g*b - sum(f != g != s[i+j] != f for i, f in e(s) for j, g in e(s[i:-1:2])))

Submission status: Accepted

Solution code:
n = int(input())
s = input()

r = s.count('R')
g = s.count('G')
b = s.count('B')
counter = 0

for i in range(n-2):
  for j in range(i+1, n-1):
    k = 2*j - i
    if k > n-1:
      break
    if s[i] != s[j] and s[j] != s[k] and s[k] != s[i]:
      counter += 1
      
print(r*g*b - counter)

Submission status: Accepted

Solution code:
N = int(input())
S = list(input())

R = 0
G = 0
B = 0

for i in range(N):
	if S[i] == 'R':
		R += 1
	elif S[i] == 'G':
		G += 1
	else:
		B += 1
ans = R * G * B
for i in range(N - 2):
	for j in range(i + 1, N - 1):
		k = j + (j - i)
		if k >= N:
			break
		if S[i] != S[j] and S[i] != S[k] and S[j] != S[k]:
			ans -= 1
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
S=input()
rgb={"R":0,"G":0,"B":0}
for s in S:
    rgb[s]+=1
sum=rgb["R"]*rgb["G"]*rgb["B"]

for i in range(0,N-2):
    for interval in range(1,(N-i+1)//2):
        if S[i]!=S[i+interval] and S[i+interval]!=S[i+2*interval] and S[i]!=S[i+2*interval]:
            sum-=1
print(sum)

Submission status: Accepted

Solution code:
N = int(input())
S = str(input())
P = 0
R = S.count('R')
G = S.count('G')
B = S.count('B')
P = R*G*B
for i in range(1,(N//2)+1):
    for j in range(N-2*i):
            if S[j]!=S[j+i] and S[j+i]!=S[j+2*i] and S[j]!=S[j+2*i]:
                P -= 1
print(P)

Submission status: Accepted

Solution code:
def sort(a,b,c):
    l=[a,b,c]
    l.sort()
    return l

n=int(input())
s=input()
r=s.count('R')
g=s.count('G')
b=s.count('B')
sum=r*g*b
for i in range(n-2):
    for j in range(i+1,n-1):
        k=2*j-i
        if k<n and s[i]!=s[j] and s[i]!=s[k] and s[j]!=s[k]:
            sum-=1
print(sum)

Submission status: Accepted

Solution code:
# Si, Sj, Skは必ずR,G,Bのどれか
# Rから1つ、Gから1つ、Bから1つ選ぶ組合せ
# Rの数 * Gの数 * Bの数 = 組合せの総数
# j-i != k-jは全体からj-i == k-jを引く
# i,jが決まるとkは2j-iと決まる

n = int(input())
S = input()

countR = S.count('R')
countG = S.count('G')
countB = S.count('B')

# R,G,Bの組み合わせ
total = countR * countG * countB

count=0
for i in range(n):
    for j in range(i+1,n):
        k = int(2*j - i)
        if k >= n:
            break
        if S[i] != S[j] and S[j] != S[k] and S[i] != S[k]:
            count+=1

total -= count

print(total)

Submission status: Accepted

Solution code:
# D - RGB Triplets
from collections import defaultdict


def main():
    _, S = open(0).read().split()
    indices, doubled_indices = defaultdict(list), defaultdict(set)
    for i, c in enumerate(S):
        indices[c].append(i)
        doubled_indices[c].add(2 * i)
    cnt = S.count("R") * S.count("G") * S.count("B")
    for x, y, z in ["RGB", "GBR", "BRG"]:
        cnt -= sum(i + j in doubled_indices[z] for i in indices[x] for j in indices[y])
    print(cnt)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# D - RGB Triplets
from collections import defaultdict


def main():
    _, S = open(0).read().split()
    indices, doubled_indices = defaultdict(list), defaultdict(set)
    for i, c in enumerate(S):
        indices[c].append(i)
        doubled_indices[c].add(2 * i)
    cnt = len(indices["R"]) * len(indices["G"]) * len(indices["B"])
    for x, y, z in ["RGB", "GBR", "BRG"]:
        cnt -= sum(i + j in doubled_indices[z] for i in indices[x] for j in indices[y])
    print(cnt)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# D - RGB Triplets
from collections import defaultdict


def main():
    _ = input()
    S = input().rstrip()
    indices, doubled_indices = defaultdict(list), defaultdict(set)
    for i, c in enumerate(S):
        indices[c].append(i)
        doubled_indices[c].add(2 * i)
    cnt = len(indices["R"]) * len(indices["G"]) * len(indices["B"])
    for x, y, z in ["RGB", "GBR", "BRG"]:
        cnt -= sum(i + j in doubled_indices[z] for i in indices[x] for j in indices[y])
    print(cnt)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# D - RGB Triplets
from collections import defaultdict


def main():
    _ = int(input())
    S = input().rstrip()
    indices, doubled_indices = defaultdict(list), defaultdict(set)
    for i, c in enumerate(S):
        indices[c].append(i)
        doubled_indices[c].add(2 * i)
    cnt = len(indices["R"]) * len(indices["G"]) * len(indices["B"])
    for c1, c2, c3 in ["RGB", "GBR", "BRG"]:
        cnt -= sum(
            i + j in doubled_indices[c3] for i in indices[c1] for j in indices[c2]
        )
    print(cnt)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# D - RGB Triplets
from collections import defaultdict


def main():
    _ = int(input())
    S = input().rstrip()
    indices = defaultdict(set)
    for i, c in enumerate(S):
        indices[c].add(2 * i)
    cnt = len(indices["R"]) * len(indices["G"]) * len(indices["B"])
    for c1, c2, c3 in ["RGB", "GBR", "BRG"]:
        cnt -= sum(
            (i + j) // 2 in indices[c3] for i in indices[c1] for j in indices[c2]
        )
    print(cnt)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# D - RGB Triplets
from collections import defaultdict


def main():
    _ = int(input())
    S = input().rstrip()
    indices = defaultdict(set)
    for i, c in enumerate(S):
        indices[c].add(i)
    cnt = len(indices["R"]) * len(indices["G"]) * len(indices["B"])
    for c1, c2, c3 in ["RGB", "GBR", "BRG"]:
        cnt -= sum(
            (i + j) % 2 == 0 and (i + j) // 2 in indices[c3]
            for i in indices[c1]
            for j in indices[c2]
        )
    print(cnt)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
def combi_three(n):
    if n < 3:
        return 0
    else:
        return int((n * (n - 1) * (n - 2)) / 6)

def quest_d():
    N = int(input())
    S = input()

    index_dict = {'R':0, 'G':0, 'B':0 }
    for index in range(N):
        index_dict[S[index]] = index_dict[S[index]] + 1

    if index_dict['R'] * index_dict['G'] * index_dict['B'] == 0:
        print(0)
        return

    rrr = combi_three(index_dict['R'])
    ggg = combi_three(index_dict['G'])
    bbb = combi_three(index_dict['B'])
    rrg = combi_three(index_dict['R'] + index_dict['G'])
    ggb = combi_three(index_dict['G'] + index_dict['B'])
    bbr = combi_three(index_dict['B'] + index_dict['R'])

    i = 0
    sum = 0
    while i < N:
        a = S[i]
        j = i
        while j < N - 1:
            j += 1
            if S[j] == a:
                continue

            k = 2 * j - i
            if k < N:
                b = S[j]
                if S[k] != a and S[k] != b:
                    sum += 1
        i += 1
    print(combi_three(N) - sum - rrg - bbr - ggb + rrr + ggg + bbb)

if __name__ == '__main__':
    quest_d()

Submission status: Accepted

Solution code:
N = int(input())
S = input()

r_num = S.count("R")
g_num = S.count("G")
b_num = S.count("B")

cnt = 0

for i in range(N - 2):
    for j in range(i + 1, N - 1):
        if not 2 * j - i < N:
            break
        if S[i] != S[j] and (S[2 * j - i] != S[i] and S[2 * j - i] != S[j]):
            cnt += 1

ans = r_num * g_num * b_num - cnt
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = input()

r_num = S.count("R")
g_num = S.count("G")
b_num = S.count("B")

cnt = 0

for i in range(N - 2):
    for j in range(i + 1, N - 1):
        if 2 * j - i < N and S[i] != S[j] and (S[2 * j - i] != S[i] and S[2 * j - i] != S[j]):
            cnt += 1

ans = r_num * g_num * b_num - cnt
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
s=input()
ans=0
r=0
g=0
b=0
rl=[]
gl=[]
bl={-2*n}
for k,i in enumerate(s):
    if i=="R":
        r+=1
        rl.append(k)
    elif i=="G":
        g+=1
        gl.append(k)
    else:
        b+=1
        bl|={k}
ans=r*b*g
for i in rl:
    for j in gl:
        if (i+j)/2 in bl:
            ans-=1
        if 2*i-j in bl:
            ans-=1
        if 2*j-i in bl:
            ans-=1
print(ans)

Submission status: Accepted

Solution code:
import sys

stdin = sys.stdin
read_int = lambda : list(map(int,stdin.readline().split()))
read_str = lambda : stdin.readline().rstrip()

N = read_int()[0]
S = read_str()

r = 0
g = 0
b = 0
for s in S:
    if s == 'R':
        r += 1
        continue
    if s == 'G':
        g += 1
        continue
    if s == 'B':
        b += 1
        continue

def solve():
    ans = r * g * b
    for d in range(1, N):
        for i in range(0, N - 2 * d):
            if S[i] != S[i + d] and S[i] != S[i + 2 * d] and S[i + d] != S[i + 2 * d]:
                ans -= 1
    return ans

if __name__ == "__main__":
    print(solve())

Submission status: Accepted

Solution code:
n = int(input())
s = input()

r = 0
g = 0
b = 0

for i in s:
    if i == 'R':
        r += 1
    elif i == 'G':
        g += 1
    else:
        b += 1

ans = r * g * b

for i in range(n-1):
    for j in range(i+1, n):
        if s[i] == s[j]: continue
        k = 2*j - i
        if k >=n: continue
        if s[i] == s[k] or s[j] == s[k]: continue
        ans -= 1

print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = input()

cnt = 0
for i in range(N):
    for j in range(1,N):
        l = i - j
        r = i + j
        if (l < 0) or (N-1 < r): break
        if (S[l] != S[i]) and (S[i] != S[r]) and (S[l] != S[r]): cnt += 1

from collections import Counter
c = Counter(S)
if len(c) < 3:
    print(0)
else:
    ans = 1
    for v in c.values(): ans *= v
    print(ans-cnt)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    s = input()
    answer = s.count("R") * s.count("G") * s.count("B")
    for i in range(n):
        for j in range(i + 1, n):
            k = 2 * j - i
            if n <= k:
                continue
            elif s[i] != s[j] and s[i] != s[k] and s[j] != s[k]:
                answer -= 1
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from sys import stdin
n = int(input())
s = stdin.readline()
r = 0
g = 0 
b = 0
for i in range(n):
    if s[i] == "R":
        r += 1
    elif s[i] == "G":
        g += 1
    else:
        b += 1
count1 = r*g*b
count2 = 0
for i in range(0,n-2):
    for j in range(i+1,n-1):
        if 2*j-i<=n-1:
            if (s[i] != s[j])and(s[i] != s[2*j-i])and(s[j] != s[2*j-i]):
               count2 += 1
print(count1-count2)

Submission status: Accepted

Solution code:
n = int(input());S = input()
r,g,b = [],[],[]
for i in range(len(S)):
    if S[i]=='R':r.append(i)
    elif S[i]=='G':g.append(i)
    else:b.append(i)
ans = len(r)*len(g)*len(b)
for r_i in r:
    for g_i in g:
        sho = min(r_i,g_i);dai = max(r_i,g_i)
        
        index = 2*sho-dai
        if index>=0:
            if S[index]=='B':ans-=1
                
        index = (sho+dai)//2
        if (sho+dai)%2 ==0:
            if S[index]=='B':ans-=1
        
        index = 2*dai-sho
        if index<len(S):
            if S[index]=='B':ans-=1
print(ans)

Submission status: Accepted

Solution code:
from math import gcd

n=int(input().strip())
s=input().strip()

r = 0
g = 0
for i in s:
    if i == 'R':
        r += 1
    elif i == 'G':
        g += 1
ans = r * g * (n - r - g)

for i in range(0, n-1):
    for d in range(1, (n - i + 1) // 2):
        if s[i] != s[i+d] and s[i] != s[i+d+d] and s[i+d] != s[i+d+d]:
            ans -= 1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
d = {'R':0, 'G':0, 'B':0}
for x in s:
    d[x] += 1
count1 = d['R']*d['G']*d['B']
maxdif = (n-1)//2
count2 = 0
for d in range(1,maxdif+1):
    for i in range(d,n-d):
        if s[i-d] != s[i] and s[i] != s[i+d] and s[i-d] != s[i+d]:
            count2 += 1
print(count1-count2)