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:
N = int(input())
S = list(input())
r,g,b = 0,0,0
k = 0
buf = 0

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

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

print(r*g*b - buf)

Submission status: Accepted

Solution code:
N = int(input())
K = list(str(input()))
R = 0
G = 0
B = 0
for i in range(N):
    if K[i] == 'R':
        R += 1
    if K[i] == 'G':
        G += 1
    if K[i] == 'B':
        B += 1

count = 0
for i in range(N-2):
    for j in range((N-3-i)//2 + 1):
        if K[i] != K[i+j+1]:
            if K[i+j+1] != K[i+j+j+2]:
                if K[i+j+j+2] != K[i]:
                    count += 1

print(R*G*B - count)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import itertools
import bisect
import sys
sys.setrecursionlimit(10 ** 7)

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

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

STR = [[] for _ in range(3)]
RGB = {'R': 0, 'G': 1, 'B': 2}
for i in range(N):
    s = S[i]
    STR[RGB[s]].append(i)

if not STR[0] or not STR[1] or not STR[2]:
    print(0)
    exit()

cnt = 0
for x, y in itertools.combinations(range(3), 2):
    for a, b in itertools.product(STR[x], STR[y]):
        if b < a:
            a, b = b, a

        c = b + (b - a)

        if N - 1 < c:
            continue

        t = RGB[S[c]]

        if t != x and t != y:
            cnt += 1

ans = len(STR[0]) * len(STR[1]) * len(STR[2]) - cnt
print(ans)

Submission status: Accepted

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

r = 0
g = 0
b = 0
for s in S:
    if s == "R":
        r += 1
    elif s == "G":
        g += 1
    else:
        b += 1

cnt = r * g * b
for i in range(N):
    for j in range(i, N):
        k = 2 * j - i
        if k >= N:
            break
        if S[i] != S[j] and S[j] != S[k] and S[i] != S[k]:
            cnt -= 1
        
print(cnt)

Submission status: Accepted

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

r_cnt = s.count('R')
g_cnt = s.count('G') 
b_cnt = s.count('B')

ans = r_cnt * g_cnt * b_cnt
cnt = 0

for i in range(n):
    for d in range(n):
        j = i + d
        k = j + d
        if k >= n:
            break
        if s[i] != s[j] and s[j] != s[k] and s[k] != s[i]:
            cnt += 1

ans = ans - cnt
print(ans)

Submission status: Accepted

Solution code:
import sys
from math import factorial
from collections import Counter
from fractions import Fraction
import heapq, bisect, fractions
import math
import itertools
sys.setrecursionlimit(10 ** 5 + 10)
INF = 10**15 +5
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))

N = INT()
S = input()
r = S.count('R')
g = S.count('G')
b = S.count('B')
res = r*g*b
for i in range(len(S)-2):
    for j in range(i+1, len(S)-1):
        if 2*j-i < len(S):
            if S[2*j-i] != S[j] and S[2*j-i] != S[i] and S[i] != S[j]:
                res -= 1

print(res)

Submission status: Accepted

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

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

# 1つ目の条件を満たす組の数
p1 = r * g * b

# 1つ目の条件を満たし、2つ目の条件を満たさない組の数
p1_not_p2 = 0
for j in range(n):
    for i in range(j):
        k = 2 * j -i
        if k <= n-1:
            if s[i] != s[j] and s[j] != s[k] and s[k] != s[i]:
                p1_not_p2 += 1

# 1つ目も2つ目も満たす組の数
print(p1 - p1_not_p2)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-


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

    R = 0
    G = 0
    B = 0

    for s in S:
        if s == 'R':
            R += 1
            continue
        elif s == 'G':
            G += 1
            continue
        elif s == 'B':
            B += 1
    

    total = 0

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

    print(R*G*B - total)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())
S = input()
from itertools import permutations
r = []
g = []
b = []
for i, s in enumerate(S):
    if s == 'R':
        r.append(i)
    elif s == 'G':
        g.append(i)
    else:
        b.append(i)

ans = len(r)*len(g)*len(b)

for A, B, C in permutations([r,g,b]):
    for i in A:
        for j in B:
            k = 2 * j - i
            if k < N and i < j < k and S[i] != S[j] and S[i] != S[k] and S[j] != S[k]: 
                ans -= 1
print(ans)

Submission status: Accepted

Solution code:
from collections import Counter

n = int(input())
s = input()
cnt = Counter(s)
ans = cnt['R'] * cnt['G'] * cnt['B']

for i in range(n):
    l = 1
    si = s[i]
    while i + l * 2 < n:
        if si != s[i + l] and si != s[i + l * 2] and s[i + l] != s[i + l * 2]:
            ans -= 1
        l += 1
print(ans)

Submission status: Accepted

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

# total number of pairs fullfilling first condition 
r = s.count('R')
g = s.count('G')
b = len(s) - r - g
total = r*g*b

# j-i = k-j
for p in range(1, (n-1)//2 + 1):
    for i in range(0, n-(2*p)):
        si, sj, sk = s[i], s[i+p], s[i+2*p]
        if si != sj and sj != sk and sk != si:
            total -=  1
print(total)

Submission status: Accepted

Solution code:
N = int(input())
S = str(input())
R,G,B = 0,0,0
for i in range(N):
    if S[i] == 'R':
        R += 1
    elif S[i] == 'B':
        B += 1
    else:
        G += 1

exc = 0
for j in range(1,N-1):
    num = 1
    while 0 <= j-num and j+num < N:
        if S[j-num] != S[j+num] and  S[j-num] != S[j] and  S[j] != S[j+num]:
            exc += 1
        num += 1

print(int(R*B*G - exc))

Submission status: Accepted

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

    ans = s.count("R") * s.count("B") * s.count("G")
    for i in range(n):
        for j in range(i, n):
            k = 2 * j - i
            if k >= n: break
            if s[i] != s[j] and s[j] != s[k] and s[i] != s[k]:
                ans -= 1

    print(ans)

if __name__ == '__main__':
    main3()

Submission status: Accepted

Solution code:
n = int(input())
s = input()
ans = s.count('R') * s.count('G') * s.count('B')
for i in range((n-3)//2+1):
    for j in range(n-3-i*2+1):
        j1 = j+i+1
        j2 = j+i*2+2
        if s[j] != s[j1] and s[j1] != s[j2] and s[j2] != s[j]:
            ans -= 1
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
from math import floor,ceil,sqrt,factorial,log
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from operator import itemgetter
from fractions import gcd
mod = 10 ** 9 + 7
inf = float('inf')
ninf = -float('inf')
 
#整数input
def ii(): return int(sys.stdin.readline().rstrip()) #int(input())
def mii(): return map(int,sys.stdin.readline().rstrip().split())
def limii(): return list(mii()) #list(map(int,input().split()))
def lin(n:int): return [ii() for _ in range(n)]
def llint(n: int): return [limii() for _ in range(n)]
#文字列input
def ss(): return sys.stdin.readline().rstrip() #input()
def mss(): return sys.stdin.readline().rstrip().split()
def limss(): return list(mss()) #list(input().split())
def lst(n:int): return [ss() for _ in range(n)]
def llstr(n: int): return [limss() for _ in range(n)]

#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？
#本当に貪欲法か？ DP法では？？

n=ii()
s=list(ss())
rarr = []
garr=[]
barr=[]

for i in range(n):
    if s[i]=="R":
        rarr.append(i)
    elif s[i]=="G":
        garr.append(i)
    else:
        barr.append(i)

#組み合わせ全通り
ans=len(rarr)*len(barr)*len(garr)

#[0, 2, 5, 11, 12, 16, 17, 18, 23, 27, 31] 11
#[4, 7, 8, 13, 20, 21, 25, 29, 35] 9
#[1, 3, 6, 9, 10, 14, 15, 19, 22, 24, 26, 28, 30, 32, 33, 34, 36, 37, 38] 19
if len(rarr)>len(garr):
    rarr,garr=garr,rarr
if len(barr)>len(garr):
    barr,garr=garr,barr

garr=Counter(garr)

for r in rarr:
    for b in barr:
        #GRB
        if r-b >0 and garr[r + r-b]:
            ans-=1
        #GBR
        elif b-r >0 and garr[b + b-r]:
            ans-=1
        #RGB BGR
        if r-b >0 and (r-b)%2==0 and garr[b+((r-b)//2)]:
            ans-=1

        elif b-r >0 and (b-r)%2==0 and garr[r+((b-r)//2)]:
            ans-=1
        #RBG
        if r-b>0 and garr[b-(r-b)]:
            ans-=1
        elif b-r>0 and garr[r-(b-r)]:
            ans-=1

print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = int(input())
s = input()
r = len([i for i in range(n) if s[i] == 'R'])
g = len([i for i in range(n) if s[i] == 'G'])
b = len([i for i in range(n) if s[i] == 'B'])
ans = r * g * b
sub = 0
for j in range(n):
    for i in range(j):
        if s[i] == s[j]:
            continue
        k = 2 * j - i
        if k >= n or ((s[i] == s[k]) or (s[j] == s[k])):
            continue
        sub += 1
print(ans - sub)

Submission status: Accepted

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

cnt_r = s.count('R')
cnt_g = s.count('G')
cnt_b = s.count('B')

ans = cnt_r * cnt_g * cnt_b

for i in range(n):
    for d in range(n):
        j = i + d
        k = j + d
        if k >= n:
            break
        if s[i] != s[j] and s[j] != s[k] and s[i] != s[k]:
            ans -= 1

print(ans)

Submission status: Accepted

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

num_r = S.count('R')
num_g = S.count('G')
num_b = S.count('B')

ans = num_r * num_g * num_b

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]:
      ans -= 1

print(ans)

Submission status: Accepted

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

nR = 0
nG = 0
nB = 0

for s in S:
    if s == "R":
        nR += 1
    elif s == "G":
        nG += 1
    elif s == "B":
        nB += 1
        
c1pat = nR*nG*nB

mcount = 0
for i in range(N-2):
    for j in range(i+1,N-1):
        k = j + (j-i)
        if k < N:
#             print(i,j,k)
            if set([S[i],S[j],S[k]]) == set(["R","G","B"]):
                mcount += 1
                
                
print(c1pat - mcount)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
dup = 0
r = s.count('R')
g = s.count('G')
b = s.count('B')

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

Submission status: Accepted

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

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 j in range(n):
        if i+j+j>=n:
            break
        s1=s[i]
        s2=s[i+j]
        s3=s[i+j*2]
        if s1!=s2 and s2!=s3 and s1!=s3:
            ans-=1
print(ans)

Submission status: Accepted

Solution code:
#pow(a,b,mod)
#np.gcd.outer
#s.count, s.replace, s.index
from math import gcd
from functools import reduce
from itertools import product ##for i in z for j in z -> for i,j in product(z,z)   ||  for i,j in product(z,repeat=2)
#slice operation: sum(ans[slice(i*2,k+1,i)]) = sum(ans[i*2:k+1:i])
from collections import defaultdict #d=defaultdict(lambda:0)  d=defaultdict(list)
n=int(input())
s=input()
 
ret=0
 
for i,x in enumerate(s):
	for j,y in enumerate(s[i+1:],start=i+1):
		if x==y:
			continue
		if i+(j-i)*2 < n :
			z=s[i+(j-i)*2]
			if y!=z!=x:
				ret-=1
 
dic=defaultdict(lambda:0)
for x in s:
	if not x in dic: 
		dic[x]=0
	dic[x]+=1

f=dic.items()
for (i,x),(j,y),(k,z) in product(f,f,f):
	if i<j<k:
		ret+=x*y*z
print(ret)

Submission status: Accepted

Solution code:
import itertools
import bisect

N = int(input())
S = input()
R_set = set()
G_set = set()
B_set = set()
R = []
G = []
B = []
R_ids = [0] * N
G_ids = [0] * N
B_ids = [0] * N

for i, s in enumerate(S):
    if s == 'R':
        R_set.add(i)
        R.append(i)
        R_ids[i] = 1
    elif s == 'G':
        G_set.add(i)
        G.append(i)
        G_ids[i] = 1
    else:
        B_set.add(i)
        B.append(i)
        B_ids[i] = 1


R_ids = list(itertools.accumulate(reversed(R_ids)))[::-1]
G_ids = list(itertools.accumulate(reversed(G_ids)))[::-1]
B_ids = list(itertools.accumulate(reversed(B_ids)))[::-1]

r = (R_set, R, R_ids)
g = (G_set, G, G_ids)
b = (B_set, B, B_ids)

def count_rgb(r, g, b):
    res = 0
    r_set, _r, r_ids = r
    g_set, _g, g_ids = g
    b_set, _b, b_ids = b
    for r_idx in _r:
        start = bisect.bisect_left(_g, r_idx)
        for g_idx in _g[start:]:
            diff = g_idx - r_idx
            num = b_ids[g_idx]
            if g_idx+diff in b_set:
                num -= 1
            res += num
    return res
            

ans = 0
for rgb in itertools.permutations((r, g, b), 3):
    ans += count_rgb(rgb[0], rgb[1], rgb[2])

print(ans)

Submission status: Accepted

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

    ans = s.count('R') * s.count('G') * s.count('B')
    for i in range(n):
        for j in range(i+1, n+1):
            k = (j - i) + j
            if k >= n:
                break
            if s[i] != s[j] and s[j] != s[k] and s[i] != s[k]:              
                ans -= 1
    print(ans)

solution()

Submission status: Accepted

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

    ans = s.count('R') * s.count('G') * s.count('B')
    for i in range(n):
        for j in range(i+1, n+1):
            k = (j - i) + j
            if k < 1 or k >= n:
                continue
            if s[i] != s[j] and s[j] != s[k] and s[i] != s[k]:              
                ans -= 1
    print(ans)

solution()

Submission status: Accepted

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

Submission status: Accepted

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

print(count)

Submission status: Accepted

Solution code:
import sys
from collections import *
import heapq
import math
from math import gcd
import bisect
import copy
from itertools import permutations,accumulate,combinations,product
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]

n=int(input())
s=input()
dic=defaultdict(list)
for i in range(n):
    if not s[i] in dic:
        dic[s[i]]=[i]
    else:
        dic[s[i]].append(i)
# print(dic)
se=set(dic["B"])
# print(se)
ans=len(dic["R"])*len(dic["G"])*len(dic["B"])
for i in range(len(dic["R"])):
    for j in range(len(dic["G"])):
        l,r=min(dic["R"][i],dic["G"][j]),max(dic["R"][i],dic["G"][j])
        if r+(r-l) in se:
            ans-=1
        if l-(r-l) in se:
            ans-=1
        if (r-l)%2==0 and l+(r-l)//2 in se:
            ans-=1
print(ans)

Submission status: Accepted

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

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

# 1つ目の条件を満たす組の数
ans = r * g * b

# 2つ目の条件を満たす組の数
c = 0
for i in range(n):
    for j in range(i+1,n):
        k = 2 * j -i
        if k > n-1:
            break
        if s[i] != s[j] and s[j] != s[k] and s[k] != s[i]:
            c += 1

print(ans - c)

Submission status: Accepted

Solution code:
def SearchCombination_RGB(Str):
    Sum_Comb = 0
    Num_R = 0
    Num_G = 0
    Num_B = 0
    for i in range(len(Str)):
        if(Str[i] =='R'):
            Num_R +=1
        elif(Str[i] == 'G'):
            Num_G += 1
        else:
            Num_B += 1
    Num_Comb = Num_R * Num_G * Num_B
    
    if(Num_Comb ==0):
        return 0
    for Pos1 in range(0, len(Str)-2):
        for Pos2 in range(Pos1+1, len(Str)-1):
            if(Str[Pos1] != Str[Pos2]):
                Pos3 = 2 * Pos2-Pos1
                if(Pos3 < len(Str) and Str[Pos3]!= Str[Pos1] and Str[Pos3] != Str[Pos2]):
                    Sum_Comb +=1

    return Num_Comb - Sum_Comb

Str = [input() for i in range(2)]
#print(Str, ", len = ", len(Str))


print( SearchCombination_RGB(Str[1].strip()) )

Submission status: Accepted

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

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

    sub = 0
    for i in range(N):
        for j in range(i + 1, N):
            k = 2 * j - i  # j-i = k-j を満たす k
            if j < k < N and S[i] != S[j] and S[i] != S[k] and S[j] != S[k]:
                sub += 1
    return total - sub

print(d_rgb_triplets())

Submission status: Accepted

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

if n<4:
    print(0)
else:
    r=0
    g=0
    ans=0
    for i in range(n):
        if s[i]=="R":
            r+=1
        elif s[i]=="G":
            g+=1
        if i>n-3:
            continue
        for k in range(1,(n-i-1)//2+1):
            if s[i]==s[i+k]:
                continue
            else:
                if s[i+k]==s[i+2*k] or s[i]==s[i+2*k]:
                    continue
                else:
                    ans-=1

    ans+=r*g*(n-r-g)
    print(max(0,ans))

Submission status: Accepted

Solution code:
n = int(input())
s = input()
c = s.count('R')*s.count('G')*s.count('B')

for i in range(n):
    for j in range(i+1,n):
        if j + j - i >= n:break
        # print(j+j-i+1)
        if s[i]!=s[j] and s[j]!=s[j+j-i] and s[i]!=s[j+j-i]:
            c-=1

print(c)

Submission status: Accepted

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

r_cnt = s.count('R')
g_cnt = s.count('G')
b_cnt = s.count('B')

ans = r_cnt * g_cnt * b_cnt

for i in range(n):
    for d in range(n):
        j = i + d
        k = j + d
        if k >= n:
            break
        if s[i] != s[j] and s[j] != s[k] and s[k] != s[i]:
            ans -= 1

print(ans)

Submission status: Accepted

Solution code:
#-------------------------------------------------------------------
import sys
def p(*_a):
  _s=" ".join(map(str,_a))
  #print(_s)
  sys.stderr.write(_s+"\n")
#-------------------------------------------------------------------
N = int(input())
S = input()

R=[]
G=set()
B=set()

from collections import defaultdict
Bd = defaultdict(lambda: -1)


for i in range(N):
	c = S[i]
	if c=='R': R.append(i)
	if c=='G': G.add(i)
	if c=='B': B.add(i)


p(R)
p(G)
p(B)

lenB = len(B)

ans=0
for i in R:
	for j in G:
		a = (i+j)/2
		b = (i*2-j)
		c = (j*2-i)
		
		x = lenB
		if (a in B): x -= 1
		if (b in B): x -= 1
		if (c in B): x -= 1
		
		ans += x

print(ans)

Submission status: Accepted

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

d = {"R": 0, "G": 0, "B": 0}
for i in range(N):
    d[S[i]] += 1
    
ans = d["R"] * d["G"] * d["B"]

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

Submission status: Accepted

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

    red, green, blue = 0, 0, 0
    for ch in S:
        if ch == 'R':
            red += 1
        elif ch == 'G':
            green += 1
        elif ch == 'B':
            blue += 1
    total = red * green * blue

    sub = 0
    for i in range(N):
        for j in range(i + 1, N):
            k = 2 * j - i  # j-i = k-j を満たす k
            if j < k < N and S[i] != S[j] and S[i] != S[k] and S[j] != S[k]:
                sub += 1
    return total - sub

print(d_rgb_triplets())

Submission status: Accepted

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

ans = 0
rgb_idx = {
    'R': [],
    'G': [],
    'B': [],
}
for i in range(n):
    if s[i] == 'R':
        rgb_idx['R'].append(i)
    elif s[i] == 'G':
        rgb_idx['G'].append(i)
    else:
        rgb_idx['B'].append(i)

for i in range(len(rgb_idx['R'])):
    for j in range(len(rgb_idx['G'])):
        ans += len(rgb_idx['B'])
        
        rnum = rgb_idx['R'][i]
        gnum = rgb_idx['G'][j]
        if gnum-rnum>0:
            g = gnum
            l = rnum
        else:
            g = rnum
            l = gnum
        dist = abs(gnum-rnum)
        if n > g+dist and s[g+dist]=='B':
            ans -= 1
        if 0 <= l-dist and s[l-dist]=='B':
            ans -= 1
        if (g+l)%2==0 and s[int((g+l)/2)]=='B':
            ans -= 1

print(ans)

Submission status: Accepted

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

ans=s.count("R")*s.count("B")*s.count("G")
for i in range(n):
    for j in range(i+1,n):
        k=2*j-i
        if k>=n:break
        if s[i]!=s[j] and s[j]!=s[k] and s[i]!=s[k]:
            ans -=1

print(ans)

Submission status: Accepted

Solution code:
n=int(input())
s=input()
r=g=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(1,n//2+2):
  for j in range(n):
    if j+i+i>=n:break
    if not(s[j]==s[j+i] or s[j+i]==s[j+i+i] or s[j]==s[j+i+i]):ans-=1
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

import sys
import math

sys.setrecursionlimit(10 ** 6)

input_line = input()
inputs = input_line.split(' ')
N, = [int(s) for s in inputs]

input_line = input()
s = list(input_line)
sl = len(s)

r = 0
g = 0
b = 0
for ss in s:
    if ss=='R':
        r += 1
    elif ss=='G':
        g += 1
    else:
        b += 1
ans = r*g*b

num = 0

for i in range(sl):
    for j in range(i+1, sl):
        k = j + (j - i)
        if k<sl:
            if s[i]!=s[j] and s[i]!=s[k] and s[j]!=s[k]:
                num += 1

ans -= num

print(ans)

Submission status: Accepted

Solution code:
#
# Written by NoKnowledgeGG @YlePhan
# ('ω')
#
#import math
#mod = 10**9+7
#import itertools
#import fractions
#import numpy as np
#mod = 10**4 + 7
"""def kiri(n,m):
  r_ = n / m
  if (r_ - (n // m)) > 0:
    return (n//m) + 1
  else:
    return (n//m)"""

""" n! mod m 階乗
mod = 1e9 + 7
N = 10000000
fac = [0] * N
def ini():
  fac[0] = 1 % mod
  for i in range(1,N):
    fac[i] = fac[i-1] * i % mod"""

"""mod = 1e9+7
N = 10000000
pw = [0] * N
def ini(c):
  pw[0] = 1 % mod
  for i in range(1,N):
    pw[i] = pw[i-1] * c % mod"""

"""
def YEILD():
  yield 'one'
  yield 'two'
  yield 'three'
generator = YEILD()
print(next(generator))
print(next(generator))
print(next(generator))
"""
"""def gcd_(a,b):
  if b == 0:#結局はc,0の最大公約数はcなのに
    return a
  return gcd_(a,a % b) # a = p * b + q"""
"""def extgcd(a,b,x,y):
  d = a
  if b!=0:
    d = extgcd(b,a%b,y,x)
    y -= (a//b) * x
    print(x,y)
  else:
    x = 1
    y = 0
  return d"""

# 最大公約数 と 最小公倍数
"""def gcd(a,b):
  if b == 0:
    return a
  return gcd(b, a % b)
def lcm(a,b):
  g = gcd(a,b)
  return (a * b) // g"""

# 二分探索
"""import bisect # 二分探索
print(A,bisect.bisect_left(A,4))
print(C,n - bisect.bisect_right(C,4))
print(sum(bisect.bisect_left(A,b) * (n-bisect.bisect_right(C,b)) for b in B))"""

# 円周率 pi
"""import math
pi_ = math.pi"""

# エラトステネスの篩
"""def Erato(n):
    prime = []
    is_prime = [True] * (n+1)
    p = 0
    is_prime[0] = False
    is_prime[1] = False
    for i in range(2,n+1):
      if is_prime[i] == True:
        prime.append(i)
        p += 1
        for j in range(2 * i,n+1,i):
          is_prime[j] = False
    return p"""

def readInts():
  return list(map(int,input().split()))
mod = 10**9 + 7
def main():
  n = int(input())
  s = input()
  t = s.count('R')*s.count('G')*s.count('B')
  for i in range(n):
    j = 1
    while i+j*2<n:
      # print(s[i],s[i+j],s[i+2*j])
      # R R G
	  # R G B こいつがあかん
      if s[i]!= s[i+j] and s[i+j]!=s[i+j*2] and s[i] != s[i+j*2]:
        t-=1
      j+=1
  print(t)

  

if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
# A: S[i], S[j], S[k] が異なるものすべて
# j-i != k-j は扱いづらいので,
# B: S[i], S[j], S[k] が異なる」かつ「j - i = k - j である」条件を探索
# ans = A-B
def resolve():
    N = int(input())
    S = input()

    # 条件1
    r, g, b = 0,0,0
    for s in S:
        if s=="R":
            r += 1
        elif s == "G":
            g += 1
        else:
            b += 1
    rgb = r*g*b
    # 条件2
    sub = 0
    for i in range(N):
        for j in range(i+1, N):
            if S[i]==S[j]:
                continue
            k = 2*j-i
            if k >= N or S[k]==S[i] or S[k]==S[j]:
                continue
            sub += 1
    return print(rgb - sub)

if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
n = int(input())
s = 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:
      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()
ans = S.count("R") * S.count("G") * S.count("B")

for i in range(N-2):
    for d in range(1, (N-i-1)//2+1):
        if {S[i], S[i+d], S[i+2*d]} == {"R", "G", "B"}:
            ans -= 1

print(ans)

Submission status: Accepted

Solution code:
# 先に組み合わせの数を決める
# RとGとBの数を先に数え上げると、Rの数 * Gの数 * Bの数が組み合わせの数になる
# 累積和でもできる

#組み合わせの数は
kumiawase = 0
countR=0
countG=0
countB=0
N = int(input())
S = list(input())
for i in range(N):
    if(S[i] == "R"):
        countR += 1
    elif(S[i] == "G"):
        countG += 1
    elif(S[i] == "B"):
        countB += 1
kumiawase = countR * countG * countB

count = 0
#その組み合わせの数から、j-i = k-jをみたす数を引けばいい
#条件を満たし、かつ1つ目の条件を満たすものは
for i in range(N):
    for j in range(i+1, N):
        k = 2 * j - i
        if(k < N):
            if(S[i] != S[j] and S[i] != S[k] and S[j] != S[k]):
                count+=1

print(kumiawase - count)

Submission status: Accepted

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

r_cnt = S.count("R")
g_cnt = S.count("G")
b_cnt = S.count("B")

total = r_cnt * g_cnt * b_cnt
diff = 0

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

def abc162d(n, s):

    r_arr = []
    g_arr = []
    b_arr = []

    for i in range(n):
        if s[i] == 'R':
            r_arr.append(i)
        elif s[i] == 'G':
            g_arr.append(i)
        else: # 'B'
            b_arr.append(i)

    min1_arr = r_arr
    min2_arr = g_arr
    max_arr = b_arr
    if len(r_arr) < len(g_arr) and len(b_arr) < len(g_arr):
        min1_arr = r_arr
        min2_arr = b_arr
        max_arr = g_arr
    elif len(g_arr) < len(r_arr) and len(b_arr) < len(r_arr):
        min1_arr = g_arr
        min2_arr = b_arr
        max_arr = r_arr

    max_dict = dict()
    for elem in max_arr:
        max_dict[elem] = 1

    except_num = 0
    for r_i in min1_arr:
        for g_i in min2_arr:
            min_i = r_i
            max_i = g_i
            if g_i < r_i:
                min_i = g_i
                max_i = r_i
            diff = max_i - min_i
            minmin = min_i - diff
            maxmax = max_i + diff
            exists_central = (max_i + min_i) % 2

            if minmin in max_dict:
                except_num += 1
            if maxmax in max_dict:
                except_num += 1
            if exists_central == 0:
                central = (max_i + min_i) / 2
                if central in max_dict:
                    except_num += 1

    ans = len(r_arr) * len(g_arr) * len(b_arr) - except_num
    return ans

###
# main
if(__name__ == '__main__'):
    # input
    n = int(input())
    s = input()
    
    ans = abc162d(n, s)
    
    # output
    print(ans)
# else:
    # do nothing

Submission status: Accepted

Solution code:
n = int(input())
s = input()
r = s.count("R");g = s.count("G");b = s.count("B")
count = r*g*b
for j in range(n):
  for i in range(j):
    if (k:=2*j-i)<n:
      if s[i]!=s[k]!=s[j]!=s[i]:
        count-=1   
print(count)

Submission status: Accepted

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

ans=s.count("R")*s.count("B")*s.count("G")
for i in range(n):
    for j in range(i,n):
        k=2*j-i
        if k>=n:break
        if s[i]!=s[j] and s[j]!=s[k] and s[i]!=s[k]:
            ans -=1

print(ans)

Submission status: Accepted

Solution code:
import sys
import math
from functools import reduce

# 入力を整数に変換して受け取る
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def MI1(): return map(int1, sys.stdin.readline().split())
# 入力全てを整数に変換したものの配列を受け取る
def LI(): return list(map(int, sys.stdin.readline().split()))
# 入力全てを整数に変換して1引いたものの配列を受け取る
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SR(): return sys.stdin.readline().rstrip()

ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_uppercase2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ'

# リストを改行区切りで出力する
p2D = lambda x: print(*x, sep="\n")
p2E = lambda x: print(''.join(x))
p2S = lambda x: print(*x, sep=" ")

def gcd_list(numbers):
    return reduce(math.gcd, numbers)

N = int(input())
S = input()
ans = S.count("R") * S.count("G") * S.count("B")
for i in range(N-2):
  for j in range(i+1,N-1):
    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)