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:
if __name__ == '__main__':
    from sys import stdin
    input = stdin.readline
    from collections import Counter

    import random

    n = int(input())
    s = input()[:-1]
    c = Counter(s)
    minus = 0
    for i in range(1,(n+1)//2):
        for j in range(n-2*i):
            if (s[j] != s[j+i]) and (s[j] != s[j+2*i]) and (s[j+i] != s[j+2*i]):
                # print(j, i)
                minus += 1

    cnt = 1
    if not 'R' in c:
        print(0)
        exit()
    if not 'G' in c:
        print(0)
        exit()
    if not 'B' in c:
        print(0)
        exit()
    for value in c.values():
        cnt *= value
    print(int(cnt-minus))
"""
    true = 0
    true_cnt = 0
    for i in range(n):
        for j in range(i+1,n):
            for k in range(j+1,n):
                if (s[i] != s[j]) and (s[i] != s[k]) and (s[j] != s[k]):
                    true_cnt += 1
                if (j-i != k-j) and (s[i] != s[j]) and (s[i] != s[k]) and (s[j] != s[k]):
                    true += 1

    print(true)
    print(true_cnt)
    print(s)
"""

Submission status: Accepted

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

rl = []
gl = []
bl = []
rld = [0]*(n)
gld = [0]*(n)
bld = [0]*(n)

for i in range(len(s)):
  if s[i] == 'R':
    rl += [i]
    rld[i] = 1 
  elif s[i] == 'G':
    gl += [i]
    gld[i] = 1 
  else:
    bl += [i]
    bld[i] = 1

rlds = rld[:]
glds = gld[:]
blds = bld[:]

for i in range(n-1, 0, -1):
  blds[i-1] += blds[i]
  rlds[i-1] += rlds[i] 
  glds[i-1] += glds[i] 

ans = 0 
for i in rl:
  for j in gl:
    if i >= j or j+1 >= n:
      continue
    ans += blds[j+1]
    if j+j-i < n:
      ans -= bld[j+j-i]

for i in rl:
  for j in bl:
    if i >= j or j+1 >= n:
      continue
    ans += glds[j+1]
    if j+j-i < n:
      ans -= gld[j+j-i]

for i in gl:
  for j in bl:
    if i >= j or j+1 >= n:
      continue
    ans += rlds[j+1]
    if j+j-i < n:
      ans -= rld[j+j-i]

for i in gl:
  for j in rl:
    if i >= j or j+1 >= n:
      continue
    ans += blds[j+1]
    if j+j-i < n:
      ans -= bld[j+j-i]
for i in bl:
  for j in gl:
    if i >= j or j+1 >= n:
      continue
    ans += rlds[j+1]
    if j+j-i < n:
      ans -= rld[j+j-i]

for i in bl:
  for j in rl:
    if i >= j or j+1 >= n:
      continue
    ans += glds[j+1]
    if j+j-i < n:
      ans -= gld[j+j-i]
    
print(ans)

Submission status: Accepted

Solution code:
def sol(a,b,nu,checker):
    if a==b:
        return None,0
    val={'R':0,'G':1,'B':-1}
    ev={0:'R',1:'G',-1:'B'}
    cal=(val[a]+val[b])*(-1)
    each=ev[cal]
    res=(checker[-1][each]-checker[nu][each])
    return each,res

n=int(input())
s=input()
#n=4000
#hoge=['R','G','B']
#s=[hoge[i%3] for i in range(n)]
#s="".join(s)
rgb_init={'R':0,'G':0,'B':0}
store=[rgb_init.copy() ]
for i,v in enumerate(s):
    tmp=store[i].copy()
    tmp[v]+=1
    store.append(tmp)

ans=0
for i in range(n):
    for j in range(i+1,n):
        al,val=sol(s[i],s[j],j+1,store)
        if (al and 2*j-i<n)and s[2*j-i]==al:
            val-=1
        ans+=val
print(ans)

Submission status: Accepted

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

R = set([v for v,i in enumerate(S) if i == 'R'])
G = set([v for v,i in enumerate(S) if i == 'G'])
B = set([v for v,i in enumerate(S) if i == 'B'])
t = len(B)
c = 0
for i in R:
    for j in G:
        d = [2* i -j,2 * j - i,(i+j)/2]
        for a,s in enumerate(d):
            if s in B:
                c -= 1
        c += t

print(c)

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

i=0
rr=[]
for R in s:
    if R=='R':
        rr.append(i)
    i+=1

j=0
gg=[]
for G in s:
    if G=='G':
        gg.append(j)
    j+=1

for rrr in rr:
    for ggg in gg:
        tmp=abs(rrr-ggg)
        if tmp%2==0:
            if max(rrr,ggg)+tmp<n:
                if s[max(rrr,ggg)+tmp]=='B':
                    ans-=1
            if s[(rrr+ggg)//2]=='B':
                ans-=1
            if min(rrr,ggg)-tmp>=0:
                if s[min(rrr,ggg)-tmp]=='B':
                    ans-=1
        else:
            if max(rrr,ggg)+tmp<n:
                if s[max(rrr,ggg)+tmp]=='B':
                    ans-=1
            if min(rrr,ggg)-tmp>=0:
                if s[min(rrr,ggg)-tmp]=='B':
                    ans-=1
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
Rcount = 0
Gcount = 0
Bcount = 0
for i in S:
    if i == "R":
        Rcount += 1
    if i == "G":
        Gcount += 1
    if i == "B":
        Bcount += 1

sum2 = Rcount * Gcount * Bcount

for i in range(1, len(S) // 2 + len(S) % 2):
    for j in range(len(S)-(i*2)):
        #print(j, j+i, j+i*2)
        if S[j] != S[j + i] and S[j] != S[j + (i * 2)] and S[j+i] != S[j+(i*2)]:
            sum2 -= 1
print(sum2)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
m = S.count('R')*S.count('G')*S.count('B')
n = 0
for i in range(0,N-2):
    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[k] != S[i]:
                n += 1
print(m-n)

Submission status: Accepted

Solution code:
from collections import Counter
N = int(input())
S = input()
c = Counter(S)

ans = c["R"] * c["G"] * c["B"]
target = sorted("RGB")
# i間隔
for i in range(1, N):
    for j in range(N):
        s1,s2,s3 = j,j+i,j+i*2
        if s2 >= N or s3 >= N:
            continue
        t = S[s1] + S[s2] + S[s3]
        if sorted(t) == target:
            ans -= 1

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
sum = 0
if n < 4:print(0);exit()
r = 0;g = 0; b = 0;
for i in range(len(s)):
    if s[i] == "R":
        r += 1
    if s[i] == "G":
        g += 1
    if s[i] == "B":
        b += 1
sum = r*g*b
for i in range(n):
    for j in range(i+1,n):
        dis = j - i
        k = j + dis
        if k >= n:break
#        print(i,j,k)
        if s[i] != s[j] and s[j] != s[k] and s[k] != s[i] :
            sum -= 1
print(sum)

Submission status: Accepted

Solution code:
n=int(input())
S=list(input())
dp=[[0]*(8) for i in range(n+1)]
dp[0][0]=1
for i in range(1,n+1):
  if S[i-1]=="R":
    for j in range(8):
      dp[i][j]=dp[i-1][j]
    dp[i][1]+=dp[i-1][0]
    dp[i][4]+=dp[i-1][2]
    dp[i][6]+=dp[i-1][3]
    dp[i][7]+=dp[i-1][5]
  elif S[i-1]=="G":
    for j in range(8):
      dp[i][j]=dp[i-1][j]
    dp[i][2]+=dp[i-1][0]
    dp[i][4]+=dp[i-1][1]
    dp[i][5]+=dp[i-1][3]
    dp[i][7]+=dp[i-1][6]
  else:
    for j in range(8):
      dp[i][j]=dp[i-1][j]
    dp[i][3]+=dp[i-1][0]
    dp[i][5]+=dp[i-1][2]
    dp[i][6]+=dp[i-1][1]
    dp[i][7]+=dp[i-1][4]
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(dp[n][7]-a)

Submission status: Accepted

Solution code:
N = int(input())
S = list(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 i in range(N):
    for d in range(1, -(-(N-i)//2)):
        if S[i] != S[i + d] and S[i + d] != S[i + 2*d] and S[i + 2*d] != S[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')
cnt = 0
for j in range(n-2):
  sj = s[j]
  for i in range(1, (n-j)//2+1):
    if n <= j+2*i:
      break
    sd = s[j+i]
    sd2 = s[j+2*i]
    if (sj != sd) and (sj != sd2) and (sd != sd2):
      cnt += 1
print(r*g*b - cnt)

Submission status: Accepted

Solution code:
def reduce(arr,n):
    count=len(arr)*(len(arr)-1)*(n-len(arr))/2+len(arr)*(len(arr)-1)*(len(arr)-2)/6
    return count

n=int(input())
s=input()

r,g,b=[],[],[]

for i,j in enumerate(s):
    if j=='R':
        r.append(i)
    elif j=='G':
        g.append(i)
    else:
        b.append(i)

count= n*(n-1)*(n-2)/6
count-=reduce(r,n)
count-=reduce(g,n)
count-=reduce(b,n)

for i in range(n):
    for j in range(i+1,n):
        if j+(j-i)<n:
            if s[i]!=s[j] and s[j]!=s[j+(j-i)] and s[i]!=s[j+(j-i)]:
                count-=1
print(int(count))

Submission status: Accepted

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

R = [0]*(n+1)
G = [0]*(n+1)
B = [0]*(n+1)

for i in range(n):
  if S[i]=='R':
    R[i+1] = 1
  if S[i]=='G':
    G[i+1] = 1
  if S[i]=='B':
    B[i+1] = 1
    
for i in range(1, n+1):
  R[i] += R[i-1]
  B[i] += B[i-1]
  G[i] += G[i-1]

ans = 0
for i in range(n):
  for j in range(i+1, n):
    color_selected = [S[i], S[j]]
    color_selected.sort()
    dif = j-i
    if color_selected == ['G', 'R']:
      ans += B[min(j+dif, n)] - B[j+1]
      ans += B[n] - B[min(j+dif+1, n)]
    elif color_selected == ['B', 'R']:
      ans += G[min(j+dif, n)] - G[j+1]
      ans += G[n] - G[min(j+dif+1, n)]
    elif color_selected == ['B', 'G']:
      ans += R[min(j+dif, n)] - R[j+1]
      ans += R[n] - R[min(j+dif+1, n)]

print(ans)

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')

total = r_cnt * g_cnt * b_cnt

for i in range(n):
    for j in range(n):
        ptr1 = j
        ptr2 = j + i
        ptr3 = j + 2 * i
        if ptr3 >= n:
            break
        else:
            if s[ptr1] != s[ptr2] and s[ptr2] != s[ptr3] and s[ptr1] != s[ptr3]:
                total -= 1

print(total)

Submission status: Accepted

Solution code:
def main():
    #from sys import stdin, setrecursionlimit
    #setrecursionlimit(10**9)
    #r = input()
    #n = int(input())
    #a, b = map(int, input().split())
    #s, y = input().split()
    #a = input().split()
    #a = list(map(int, input().split()))
    #a = [list(input().split()) for i in range(n)]
    #a = [int(input()) for i in range(n)]
    #a = [list(map(int, input().split())) for i in range(n)]
    #a = [int(s) - 1 for s in input().split()]
    #l=[int(input()) for _ in range(int(input()))]
    #res = 0
    n=int(input())
    s=list(input())
    if len(set(s)) < 3:
      print(0)
      return 0
    from collections import Counter
    c=Counter(s)
    res=c['R']*c['G']*c['B']

    for j in range(1,n):
      for w in range(0,n+1):
        i=j-w
        k=j+w

        if i<0 or k>=n:
          continue
        if s[i]!=s[j] and s[i]!=s[k] and s[j]!=s[k]:
          res-=1
    print(res)
    return 0

if __name__ == '__main__':
    main()

Submission status: Accepted

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

ans = 0

Rc = S.count("R")
Gc = S.count("G")
Bc = S.count("B")

Rp = 0
Gp = 0

for i in range(Rc):
  while S[Rp] != "R":
    Rp += 1
  for j in range(Gc):
    ad = 0

    while S[Gp] != "G":
      Gp += 1
    
    if  min(Rp,Gp)-abs(Rp-Gp) >= 0 :
      if S[min(Rp,Gp)-abs(Rp-Gp)] == "B":
        ad += 1
    if max(Rp,Gp)+abs(Rp-Gp) < N :
      if S[max(Rp,Gp)+abs(Rp-Gp)] == "B":
        ad += 1
    if (Rp + Gp)//2 == (Rp + Gp)/2:
      if S[(Rp + Gp)//2] == "B":
        ad += 1

    
    ans += Bc - ad

    Gp += 1

  Rp += 1
  Gp = 0


print(ans)

Submission status: Accepted

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

csum = {
  'R': [0]*(N+1),
  'G': [0]*(N+1),
  'B': [0]*(N+1)
}
for i, c in enumerate(S):
  for k in csum.keys():
    csum[k][i+1] = csum[k][i]
  csum[c][i+1] += 1

ans = 0
for j in range(1, N-1):
  for i in range(j):
    if S[i] == S[j]: continue
    s = set('RGB') - {S[i], S[j]}
    s = s.pop()
    diff = j-i
    cand = csum[s][-1] - csum[s][j]
    if j+diff < N and S[j+diff] == s: cand -= 1
    ans += cand
    
print(ans)

Submission status: Accepted

Solution code:

n = int(input())
s = input()

numR = 0
numG = 0
numB = 0

for _s in s:
	if _s == "R":
		numR += 1
	if _s == "G":
		numG += 1
	if _s == "B":
		numB += 1

ans = numR * numB * numG

for inv in range((len(s)-1)//2+1):
	if inv == 0:
		continue
	for ck in range(len(s)-(inv*2+1)+1):
		if s[ck] != s[ck+inv] and s[ck] != s[ck+inv*2] and s[ck+inv] != s[ck+inv*2]:
			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")

cnt = 0
k = 1
while 2*k + 1 <= N:
  for i in range(N - 2*k):
    if S[i] != S[i + k] and S[i + k] != S[i + 2*k] and S[i + 2*k] != S[i]:
      cnt += 1
  k += 1
print(r*g*b - cnt)

Submission status: Accepted

Solution code:
def main():
    x = int(input())
    s = list(input())

    n_r = s.count('R')
    n_g = s.count('G')
    n_b = s.count('B')
    sum = n_r * n_g * n_b
    for i in range(len(s)):
      for j in range(i+1):
        if j > 0 and i + j < x:
          if s[i-j] != s[i] and s[i] != s[i+j] and s[i-j] != s[i+j]:
            sum -= 1
    print(sum)
main()

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    s = list(input())
    r = [0] * n
    g = [0] * n
    b = [0] * n
    # print(s)
    for i, rgb in enumerate(s):
        if rgb == 'R':
            r[i] += 1
        elif rgb == 'G':
            g[i] += 1
        else:
            b[i] += 1

        if i != 0:
            r[i] += r[i-1]
            g[i] += g[i-1]
            b[i] += b[i-1]
    # print(r)
    ans = 0
    mid = [0] * n
    # print('A')
    for i, rgb in enumerate(s):
        # print(i)

        # print('A')
        for j in range(1,i+1):
            # print(i,j,rgb)
            if i+j >= n or i-j < 0:
                break
            # print(s[i-j],rgb,s[i+j])
            if rgb != s[i-j] and s[i-j] != s[i+j] and rgb != s[i+j]:
                mid[i] += 1



    # print(mid)
    for i, ss in enumerate(s):
        if i == 0:
            continue
        if ss == 'R':
            tmp = g[i-1] * (b[-1] - b[i])
            tmp += b[i-1] * (g[-1] - g[i])
            tmp -= mid[i]
        elif ss == 'G':
            tmp = r[i-1] * (b[-1] - b[i])
            tmp += b[i-1] * (r[-1] - r[i])
            tmp -= mid[i]
        else:
            tmp = g[i-1] * (r[-1] - r[i])
            tmp += r[i-1] * (g[-1] - g[i])
            tmp -= mid[i]
        ans += tmp
    print(ans)

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
#import sys
MOD = 10 ** 9 + 7
INFI = 10**10
#input = sys.stdin.readline
import math

import itertools
import heapq
#import bisect

import copy
from functools import lru_cache

def sosuhante(n):
    for k in range(2, int(math.sqrt(n))+1):
        if n% k ==0:
            return False
    return True
def cmb(n, r):
    if n - r < r: r = n - r
    if r == 0: return 1
    if r == 1: return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])

    return result

def kingaku(a,b,n):
    keta=len(str(n))
    return a*n+b*keta

def my_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default

#    h,w,a,b = map(int, input().split())
#    c = [[0 for j in range(n)] for i in range(n)]

def ret(a):
    c=[None]*(len(a)-1)
    if len(a)==1:
        return a[0]
    elif len(a)==0:
        return 0
    for i in range(1,len(a)):
        c[i-1]=abs(a[i]-a[i-1])
    return ret(c)


def main():
    n=int(input())
    s=list(input())
    for i in range(n+3):
        s.append("A")
    rr=0
    rg=0
    rb=0
    for i in range(n):
        if s[i]=="R":
            s[i]=-1
            rr+=1
        elif s[i]=="G":
            s[i]=1
            rg+=1
        elif s[i]=="B":
            s[i]=0
            rb+=1
    total=0
    for i in range(n-1):
        for j in range(i+1,n):
            if s[i]!=s[j]:
                if s[j*2-i]==(-1)*(s[i]+s[j]):
                    total-=1
    total+=rr*rg*rb


    print(total)



if __name__ == "__main__":

    main()

Submission status: Accepted

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

ans = 0
b_l = [0] * n
g_l = [0] * n
r_l = [0] * n
for i in range(n):
    if s[i] == 'B':
        b_l[i] = 1
    if s[i] == 'G':
        g_l[i] = 1
    if s[i] == 'R':
        r_l[i] = 1
# print(b_l)
# print(g_l)
b_s = [0] * n
g_s = [0] * n
r_s = [0] * n
b_s[0] = b_l[0]
g_s[0] = g_l[0]
r_s[0] = r_l[0]
for i in range(1, n):
    b_s[i] = b_s[i-1] + b_l[i]
for i in range(1, n):
    g_s[i] = g_s[i-1] + g_l[i]
for i in range(1, n):
    r_s[i] = r_s[i-1] + r_l[i]
# print(b_s)
# print(g_s)
for i in range(n):
    # print(b_s[n-1] - b_s[i])
    # print(g_s[n-1] - g_s[i])
    # print((b_s[n-1] - b_s[i]) * (g_s[n-1] - g_s[i]))
    if s[i] == 'R':
        ans += (b_s[n-1] - b_s[i]) * (g_s[n-1] - g_s[i])
    if s[i] == 'B':
        ans += (r_s[n-1] - r_s[i]) * (g_s[n-1] - g_s[i])
    if s[i] == 'G':
        ans += (b_s[n-1] - b_s[i]) * (r_s[n-1] - r_s[i])
# print('ans', ans)

for i in range(n):
    for j in range(n):
        if i - j >= 0 and i + j < n:
            letters = {s[i-j], s[i], s[i+j]}
            if len(letters) == 3:
                ans -= 1
                # print(i, j)
# print('ans', ans)
print(ans)

Submission status: Accepted

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

r_count=0
g_count=0
b_count=0

ans = 0

for i in range(n):
    if s[i]=="R":
        r_count+=1
    if s[i]=="G":
        g_count+=1
    if s[i]=="B":
        b_count+=1
ans+=r_count*g_count*b_count

t=int(n-(0.1)//2)
for i in range(1,t):
    for j in range(n-2*i):
        s_1 = s[j]
        s_2 = s[j+i]
        s_3 = s[j+i+i]
        if s_1 !=s_3 and s_2!=s_3 and s_1!=s_2:
            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(1,n//2+10):
  j = 0
  while j+2*i <= n-1:
    if s[j] != s[j+i] and s[j] != s[j+2*i] and s[j+i] != s[j+2*i]:
      ans -= 1
    j += 1
print(ans)

Submission status: Accepted

Solution code:
from collections import Counter

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

count = Counter(S)
R_list = [count[0]] * N
G_list = [count[0]] * N
B_list = [count[0]] * N
R_count = 0
G_count = 0
B_count = 0
for i in range(1, len(S)+1):
    if S[-i] == 'R':
        R_count += 1
    elif S[-i] == 'G':
        G_count += 1
    else:
        B_count += 1
    R_list[-i] = R_count
    G_list[-i] = G_count
    B_list[-i] = B_count

amount = 0
for i, s in enumerate(S):
    for k in range(i+1, len(S)):
        if S[i] == S[k]:
            continue
        else:
            check_set = set([S[i], S[k]])
            if 'R' not in check_set:
                amount += R_list[k]
            elif 'G' not in check_set:
                amount += G_list[k]
            else:
                amount += B_list[k]
            try:
                if S[2*k-i] not in check_set:
                    amount -= 1
            except:
                pass
print(amount)

Submission status: Accepted

Solution code:
n=int(input())
s=input()
Rs,Gs,Bs=[],[],[]

for i in range(n):
    if s[i]=='R':
        Rs.append(i)
    elif s[i]=='G':
        Gs.append(i)
    else:
        Bs.append(i)

ans=len(Rs)*len(Gs)*len(Bs)
for i in Rs:
    for j in Gs:
        dis=abs(i-j)
        a=min(i,j)-dis
        b=max(i,j)+dis
        c=min(i,j)+dis//2
        if a>=0:
            if s[a]=='B':
                ans-=1
        if b<n:
            if s[b]=='B':
                ans-=1
        if dis%2==0:
            if s[c]=='B':
                ans-=1

print(ans)

Submission status: Accepted

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

rr = [0]*N
gr = [0]*N
br = [0]*N

r = 0
g = 0
b = 0
for i in range(N-1, -1, -1):
    if S[i] == "R":
        r += 1
    if S[i] == "G":
        g += 1
    if S[i] == "B":
        b += 1
    rr[i] = r
    gr[i] = g
    br[i] = b

wa = {"R":rr, "G":gr, "B":br}

res = 0

for i in range(N):
    c1 = S[i]
    for j in range(i+1, N):
        c2 = S[j]
        if c1 == c2:
            continue
        c = (c1, c2)
        if "R" not in c:
            c3 = "R"
        elif "G" not in c:
            c3 = "G"
        else:
            c3 = "B"

        if wa[c3][j] == 0:
            break

        res += wa[c3][j]
        x = i+(j-i)*2
        if x < N:
            if S[x] == c3:
                res -= 1
                pass

print(res)

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict
d = defaultdict(str)
N = int(sys.stdin.readline())
S = sys.stdin.readline()

ans = 0
k = 'RGB'
for i in range(N):
	for j in range(i+1,N):
		if not S[i]==S[j]:
			tmp =k.replace(S[i],'')
			tmp = tmp.replace(S[j],'')
			if d[str(j+1)+tmp]=='':
				p = S[j+1:].count(tmp)
				d[str(j+1)+tmp] = p
				ans += p
				if 2*j-i<N and S[2*j-i]==tmp:
					ans-= 1
					
			else:
				ans +=d[str(j+1)+tmp]
				if 2*j-i<N and S[2*j-i]==tmp:
					ans -=1
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_tuple(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


def read_col(H, n_cols):
    '''
    H is number of rows
    n_cols is number of cols
    A列、B列が与えられるようなとき
    '''
    ret = [[] for _ in range(n_cols)]
    for _ in range(H):
        tmp = list(map(int, read().split()))
        for col in range(n_cols):
            ret[col].append(tmp[col])
    return ret


def read_matrix(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


def read_map(H):
    '''
    H is number of rows
    文字列で与えられた盤面を読み取る用
    '''
    return [read()[:-1] for _ in range(H)]


def read_map_as_int(H):
    '''
    #→1,.→0として読み込む
    '''
    ret = []
    for _ in range(H):
        ret.append([1 if s == '#' else 0 for s in read()[:-1]])
        # 内包表記はpypyでは若干遅いことに注意
        # #numpy使うだろうからこれを残しておくけど
    return ret


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right
from math import gcd


def lcm(a, b):
    # 最小公倍数
    g = gcd(a, b)
    return a * b // g


N = read_a_int()
S = read()[:-1]
# 3文字選んで全部違う文字かつ、同じ分離れてるものじゃない
# 全通り-同じ分離れてる通り

# 全通り→sum_i i文字
# i文字目は何通りできるか？→(i:]文字の中でi文字目と違う文字の数nに対してnC2

# 同じ分離れている通り(削除する分)はどうやって数えるか？
# →O(n^2)かけてスライドさせて見てみるか...
# n_diff = []  # i文字目と違う文字が何文字あるか
n_r = S.count('R')
n_g = S.count('G')
n_b = S.count('B')
tmp = {'R': n_r,
       'G': n_g,
       'B': n_b}
total = 0
for s in S:
    tmp[s] -= 1
    if s == 'R':
        n_diff = tmp['G'] * tmp['B']
    elif s == 'G':
        n_diff = tmp['R'] * tmp['B']
    if s == 'B':
        n_diff = tmp['G'] * tmp['R']
    total += n_diff


# O(nn)かけて条件を満たさない個数を探す
# 条件がないときに違う組み合わせの通りの数はわかっている
# 条件を満たしてしまうときは？組み合わせの中で
rem = 0
for add in ra(1, N + 1):
    if add * 2 >= N:
        break
    for i in ra(N):
        j = i + add
        k = j + add
        if k >= N:
            break
        # if S[i] == S[j] or S[j] == S[k] or S[k] == S[i]:
        if S[i] != S[j] and S[j] != S[k] and S[k] != S[i]:

            # print(i, j, k)
            # print(S[i], S[j], S[k])
            rem += 1

print(total - rem)
# print(total, rem)

Submission status: Accepted

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

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

for i, c in enumerate(S, start=1):
    if c == 'R':
        R.append(i)
    if c == 'G':
        G.append(i)
    if c == 'B':
        B.append(i)

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

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

print(ans)

Submission status: Accepted

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

c = 'RGB'
cnt = [[0 for _ in range(n + 1)] for _ in range(3)]
for i in range(n - 1, -1, -1):
     for j in range(3):
         cnt[j][i] = cnt[j][i + 1]
         if s[i] == c[j]:
             cnt[j][i] += 1
ans = 0
for i in range(n - 3):
    for j in range(i + 1, n - 1):
        if s[i] == s[j]:
            continue
        for k in range(3):
            if s[i] == c[k] or s[j] == c[k]:
                continue
            ans += cnt[k][j + 1]
            if 2 * j - i < n and s[2 * j - i] == c[k]:
                ans -= 1
print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
read = sys.stdin.read


#p,n,k,b,*a = [int(i) for i in read().split()]

n = int(input())
s = input()

ans = 0
from itertools import permutations
L = ["R","G","B"]
ans = 0
for p in permutations(L):
    dpr = dpg = dpb = 0
    x = p[0]
    y = p[1]
    for i in s:
        if i == x:
            dpr += 1
        elif i == y:
            dpg += dpr
        else:
            dpb += dpg
    ans += dpb

#print(ans)

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

Submission status: Accepted

Solution code:
n=int(input())
s=input()
cnt=0
r_num=0
g_num=0
b_num=0
for i in s:
  if i=="R":
    r_num+=1
  if i=="G":
    g_num+=1
  if i=="B":
    b_num+=1
cnt=r_num*g_num*b_num

for i in range(1,n):
  l=i-1
  r=i+1
  while l>=0 and r<=n-1:
    if s[l]!=s[i] and s[i]!=s[r] and s[l]!=s[r]:
      cnt-=1
    l-=1
    r+=1
print(cnt)

Submission status: Accepted

Solution code:
### ----------------
### ここから
### ----------------

import sys
from io import StringIO
import unittest

def yn(b):
    print("Yes" if b==1 else "No")
    return

def resolve():
    readline=sys.stdin.readline

    #n,m,k=map(int, readline().rstrip().split())
    #arr=list(map(int, readline().rstrip().split()))
    n=int(readline())
    ss=readline().rstrip()
    #yn(1)
    rn=[0]*n
    gn=[0]*n
    bn=[0]*n

    for i in range(n):
        if i>0:
            rn[i]=rn[i-1]
            gn[i]=gn[i-1]
            bn[i]=bn[i-1]

        if ss[i]=="R":
            rn[i]+=1
        elif  ss[i]=="G":
            gn[i]+=1
        else:
            bn[i]+=1
    rsum=rn[n-1]
    gsum=gn[n-1]
    bsum=bn[n-1]

    ans=rsum*gsum*bsum
    w=0
    for d in range(1,4000):
        for i in range(n):
            a=i
            b=i+d
            c=b+d
            if a>=n or b>=n or c>=n:
                if i==0:
                    print(ans-w)
                    return
                break
            if ss[a]!=ss[b] and ss[a]!=ss[c] and ss[b]!=ss[c]:
                w+=1

    return

if 'doTest' not in globals():
    resolve()
    sys.exit()

### ----------------
### ここまで 
### ----------------

Submission status: Accepted

Solution code:
def split(word):
    return [char for char in word]
N=int(input())
S=input()
Slist=split(S)
Rcounter=0
Bcounter=0
Gcounter=0
for i in range(0,N):
    if Slist[i]=='R':
        Rcounter=Rcounter+1
    if Slist[i]=='B':
        Bcounter=Bcounter+1
    if Slist[i]=='G':
        Gcounter=Gcounter+1
ans=Rcounter*Gcounter*Bcounter
for i in range(0,N):
    for j in range(i+1,N):
        if 2*j-i>N-1:
            break
        if (Slist[i]==Slist[j]) or (Slist[i]==Slist[2*j-i]) or (Slist[j]==Slist[2*j-i]):
            continue
        ans=ans-1
print(ans)

Submission status: Accepted

Solution code:
#coding:utf-8
import sys,os
from collections import defaultdict, deque
from fractions import gcd
from math import ceil, floor
sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = (lambda *something: print(*something)) if 'TERM_PROGRAM' in os.environ else lambda *x: 0
def main(given=sys.stdin.readline):
    input = lambda: given().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    XLMIIS = lambda x: [LMIIS() for _ in range(x)]
    YN = lambda c : print('Yes') if c else print('No')
    MOD = 10**9+7

    N = II()
    S = input()
    sum_d = 0
    for d in range(1,N//2+1):
        for i in range(N-2*d):
            if S[i] != S[i+d] and S[i+d] != S[i+2*d] and S[i+2*d] != S[i]:
                sum_d += 1

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

    print(max(r*g*b-sum_d,0))



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import Counter
N = int(input())
S = input()
#c = Counter(S)
#print (c.most_common())
#ls = list(c.values())
ans = S.count('R') * S.count('G') * S.count('B')


for i in range(N):
    for j in range(1,N):
        if (i-j<0 or i+j>=N):
            break
        #print (i,j)
        #s = set([S[i-j],S[i],S[i+j]])
        l = S[i-j]
        m = S[i]
        r = S[i+j]

        if l!=m and m!=r and r!=l:
            ans -= 1
        # if len(s)==3:
        #     ans -= 1
print (ans)

Submission status: Accepted

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


def solve(N: int, S: str):
    dp = [[0] * (3 * N) for _ in range(3)]
    d = dict(zip('RGB', range(3)))
    dd = dict(zip(range(3), 'RGB'))
    S = [d[s] for s in S]
    for i in range(3):
        for j in range(N-1, -1, -1):
            dp[i][j] = dp[i][j+1] + (1 if S[j] == i else 0)
    #print(*dp, sep='\n')
    def f():
        for i in range(N-2):
            for j in range(i+1, N-1):
                c1, c2 = S[i], S[j]
                if c1 == c2:
                    continue
                c3 = 3 - c1 - c2
                di = j - i
                #print((i, j), dd[c1], dd[c2], dd[c3], j+1, j+di, j+di+1)
                #print(dp[c3][j+1], dp[c3][j+di])
                yield dp[c3][j+1] - dp[c3][j+di]
                yield dp[c3][j+di+1]
    print(sum(f()))


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    S = next(tokens)  # type: str
    solve(N, S)

if __name__ == '__main__':
    main()