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:
def main():
    n = int(input())
    s = list(input())
    sr = [0] * n
    sg = [0] * n
    sb = [0] * n
    for i1 in range(n):
        ts = s[i1]
        if ts == 'R':
            sr[i1] = 1
        elif ts == 'G':
            sg[i1] = 1
        else:
            sb[i1] = 1
    if n <= 3:
        print(0)
        exit()
    r = 0
    for ia in range(0,n-3):
        ta = s[ia]
        if ta == 'R':
            r += sum(sg[ia+1:]) * sum(sb[ia+1:])
        elif ta == 'G':
            r += sum(sr[ia+1:]) * sum(sb[ia+1:])
        else:
            r += sum(sg[ia + 1:]) * sum(sr[ia + 1:])
        for ib in range((n - ia)//2+1):
            if ia + ib * 2 < n:
                if ta != s[ia + ib] and ta != s[ia + ib + ib] and s[ia+ib]!= s[ia + ib + ib]:
                    r -= 1
    print(r)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict

n = int(input())
s = input()
d = defaultdict(list)
has = defaultdict(set)
for i, c in enumerate(s):
    d[c].append(i)
    has[c].add(i)
ret = 0
for i in range(n):
    for j in range(i + 1, n):
        if s[i] == s[j]:
            continue
        need = list({'R', 'G', 'B'} - {s[i], s[j]})[0]
        a = d[need]
        left, right = -1, len(a)
        while left + 1 < right:
            mid = (left + right) >> 1
            if a[mid] <= j:
                left = mid
            else:
                right = mid
        if right != len(a):
            bad = j + j - i
            ret += len(a) - right - (bad in has[need])
print(ret)

Submission status: Accepted

Solution code:
import collections

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

dic = collections.Counter(S)

# RGBの選び方
cnt = 1
c = 0
for k, v in dic.items():
    c += 1
    cnt *= v

if v == 0 or c != 3:
    print(0)
else:
    for j in range(1, N - 1):
        mm = min(j, N - j - 1)
        for d in range(1, mm + 1):
            if S[j - d] != S[j] and S[j] != S[j + d] and S[j - d] != S[j + d]:
                cnt -= 1

    print(cnt)

Submission status: Accepted

Solution code:
from collections import Counter

input()
s = input()
try:
  x, y, z = Counter(s).values()
  print(x * y * z - sum(s[i] != s[(i + j) // 2] != s[j] != s[i]
                        for i in range(len(s)) for j in range(i % 2, i, 2)))
except ValueError:
  print(0)

Submission status: Accepted

Solution code:
from collections import Counter

N = int(input())
S = input()
index = Counter(S)
ans = index["R"]*index["G"]*index["B"]

for diff in range(1, N//2 +1):
    for i in range(N):
        j = i +diff
        k = j +diff
        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:
#MLE注意！

def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    #from collections import defaultdict
    from itertools import combinations, permutations, accumulate, groupby
    #from itertools import product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    from math import floor, ceil
    #from operator import itemgetter

    #inf = 10**17
    #mod = 10**9 + 7

    n = int(input())
    s = input().rstrip()
    res = s.count('R') * s.count('G') * s.count('B')

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

    print(res - cnt)

if __name__ == '__main__':
    main()

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):
            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)
main()

Submission status: Accepted

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

r_list = []
g_list = []
for _ in range(n):
    if s[_] == "R":
        r_list.append(_)
    elif s[_] == "G":
        g_list.append(_)

count = 0
for r in r_list:
    for g in g_list:
        if min(r, g) - abs(r - g) > 0:
            if s[min(r, g) - abs(r - g)] == "B":
                count += 1
        if max(r, g) + abs(r - g) < n:
            if s[max(r, g) + abs(r - g)] == "B":
                count += 1
        if (r + g) % 2 == 0:
            if s[(r + g) // 2] == "B":
                count += 1


print(len(r_list) * len(g_list) * (n - len(r_list) - len(g_list)) - count)

Submission status: Accepted

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

cnt = 0
for i in range(n):
    for j in range(1, (n - 1) // 2 + 1):
        if n - 1 < i + 2 * j:
            break
        
        if s[i] != s[i + j] and s[i + j] != s[i + 2 * j] and s[i + 2 * j] != s[i]:
            cnt += 1
            continue
        
ans = [0] * 3
for word in s:
    if word == 'R':
        ans[0] += 1
    elif word == 'G':
        ans[1] += 1
    else:
        ans[2] += 1

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

Submission status: Accepted

Solution code:
import collections

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

c = collections.Counter(S)

ans = c['R'] * c['G'] * c['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 k < N and S[k] != S[i] and S[k] != S[j]:
                ans -= 1
print(ans)

Submission status: Accepted

Solution code:
from itertools import product as pro

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

r = [i for i in range(n) if s[i] == 'R']
g = [i for i in range(n) if s[i] == 'G']
b = [i for i in range(n) if s[i] == 'B']
cnt = len(r) * len(g) * len(b)

max1=set(b)

for i, j in pro(r, g):
    if 2*j-i in max1:
        cnt -= 1
    if 2*i-j in max1:
        cnt -= 1
    if (i+j)/2 in max1:
        cnt -= 1

print(cnt)

Submission status: Accepted

Solution code:
n=int(input())
s=input()
r,g,b=0,0,0
for i in range(n):
    if s[i]=="R":
        r+=1
    elif s[i]=="G":
        g+=1
    else:
        b+=1
chohuku=0
double=0
for i in range(1,n-1):
    for j in range(1,min(i+1,n-i)):
        chohuku+=1
        k=j+i
        l=i-j
        if s[i]!=s[k] and s[i]!=s[l] and s[l]!=s[k]:
            double+=1
ans=r*g*b-double
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
word = list(input())
ans = 0
for i in range(1,(N-1)//2+1):
    for j in range(N-2*i):
        if word[j] != word[j+i] and word[j] != word[j+2*i] and word[j+i] != word[j+2*i]:
            ans -= 1

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

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
#from collections import defaultdict
#d = defaultdict(int)
#import fractions
#import math
#import collections
#from collections import deque
#from bisect import bisect_left
N = int(input())
#A = list(map(int,input().split()))
S = list(input())
#S.remove("\n")
#N,M = map(int,input().split())
#S,T = map(str,input().split())
#A = [int(input()) for _ in range(N)]
#S = [input() for _ in range(N)]
#A = [list(map(int,input().split())) for _ in range(N)]
R = []
G = []
B = []
for i in range(N):
    a = S[i]
    if a == "R":
        R.append(i)
    elif a == "G":
        G.append(i)
    else:
        B.append(i)
s = len(R) * len(G) * len(B)
def binary_search(S,key):  #昇順リストSからkeyを探す。
    n = len(S)             #存在したらindex,なかったら-1を返す
    left  = 0
    right = n
    while left < right:
        mid = (left+right) // 2
        if S[mid] == key:
            return mid
        elif S[mid] > key:
            right = mid
        else:
            left = mid + 1
    return -1
for r in R:
    for g in G:
        Min = min(r,g)
        Max = max(r,g)
        if 2 * Min - Max > 0:
            c1 = 2 * Min - Max
        else:
            c1 = -1
        if (Min + Max ) % 2 == 0:
            c2 = (Min + Max) / 2
        else:
            c2 = -1
        if 2 * Max - Min < N:
            c3 = 2 * Max - Min
        else:
            c3 = -1
        if c1 != -1:
            if binary_search(B,c1) != -1:
                s -= 1
        if c2 != -1:
            if binary_search(B,c2) != -1:
                s -= 1
        if c3 != -1:
            if binary_search(B,c3) != -1:
                s -= 1
print(s)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
r = s.count("R")
g = s.count("G")
b = s.count("B")
ret = 0
for i in range(1,n-1):
    m = min(i,n-i-1)
    for j in range(1,m+1):
        A,B,C = s[i],s[i-j],s[i+j]
        if A != B and A != C and B != C:
            ret += 1
ans = r*g*b - ret
print(ans)

Submission status: Accepted

Solution code:
# これは, u749194f さんの改造です。
# オリジナルではございません。
# https://atcoder.jp/contests/abc162/submissions/11825963
n = int(input())
s = input()
flag = True
if len(set(s))<=2:
    print(0)
    flag = False
if flag:
    r = [i+1 for i in range(n) if s[i]=='R']
    b = [i+1 for i in range(n) if s[i]=='B']
    g = [i+1 for i in range(n) if s[i]=='G']
    minus = 0
    def cnt_cmb(a, b, c):
        cnt = 0
        set_c = set(c)
        for i in a:
            for j in b:
                if (i+j)/2 in set_c:
                    cnt += 1
        return cnt
    minus += cnt_cmb(r, b, g)
    minus += cnt_cmb(b, g, r)
    minus += cnt_cmb(g, r, b)
    print(len(r)*len(b)*len(g)-minus)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
 
def im(l, x):
    return [i for i, _x in enumerate(l) if _x == x]
R = im(S, "R")
G = im(S, "G")
B = im(S, "B")
 
ext = 0
if N >= 3:
    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] != S[j+2*(i+1)] and S[j+i+1] != S[j+2*(i+1)]:
                ext += 1
 
ans = len(R)*len(G)*len(B) - ext
print(ans)

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={"R":[],"G":[],"B":[]}
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:
from collections import Counter
# これは, u749194f さんの改造です。
# オリジナルではございません。
# https://atcoder.jp/contests/abc162/submissions/11825963
n = int(input())
s = input()
flag = True
if len(set(s))<=2:
    print(0)
    flag = False
if flag:
    r = [i+1 for i in range(n) if s[i]=='R']
    b = [i+1 for i in range(n) if s[i]=='B']
    g = [i+1 for i in range(n) if s[i]=='G']
    minus = 0
    def cnt_cmb(a, b, c):
        cnt = 0
        set_c = set(c)
        for i in a:
            for j in b:
                if (i+j)/2 in set_c:
                    cnt += 1
        return cnt
    minus += cnt_cmb(r, b, g)
    minus += cnt_cmb(b, g, r)
    minus += cnt_cmb(g, r, b)
    a = Counter(s)
    rslt = 1
    for value in a.values():
        rslt *= value
    print(len(r)*len(b)*len(g)-minus)

Submission status: Accepted

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

count = 0
r = []
g = []
b = []

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

count += len(r)*len(g)*len(b)

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

Submission status: Accepted

Solution code:
from collections import Counter

def main():
    n = int(input())
    s = list(input())

    t = Counter(s)

    ans = t['R']*t['G']*t['B']

    for i in range(n):
        for j in range(n):
            if i+j*2<n:
                if s[i]!=s[i+j] and s[i+j]!=s[i+j*2] and s[i]!=s[i+j*2]:
                    ans-=1
            else:
                break
    print(ans)
if __name__ == "__main__":
    main()

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 and S[k]!=S[i] and S[k]!=S[j] and S[j]!=S[i]:
            ans-=1
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
S = input()
r = []
g = []
b = []
for i, s in enumerate(S):
    if s == 'R':
        r.append(i+1)
    elif s == 'G':
        g.append(i+1)
    else:
        b.append(i+1)

lenr = len(r)
leng = len(g)
lenb = len(b)
total = lenr*leng*lenb
for i in range(0, n-2):
    for j in range(n-(i+1)*2):
        j1 = j+i+1
        j2 = j+i*2+2
        if (S[j] != S[j1]) and (S[j1] != S[j2]) and (S[j2] != S[j]):
            total -= 1
print(total)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def main():
    n=int(input())
    s=input()
    r=[]
    g=[]
    b=[]
    rdict={}
    gdict={}
    bdict={}
    ans=0
    for i in range(n):
        if s[i]=='R':
            r.append(i)
            rdict[2*i]=2*i
        if s[i]=='G':
            g.append(i)
            gdict[2*i]=2*i
        if s[i]=='B':
            b.append(i)
            bdict[2*i]=2*i
    ans=len(r)*len(g)*len(b)
    for i in r:
        for j in g:
            if i+j in bdict:
                ans-=1
    for i in g:
        for j in b:
            if i+j in rdict:
                ans-=1
    for i in b:
        for j in r:
            if i+j in gdict:
                ans-=1
    print(ans)
    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import heapq
from collections import defaultdict, deque
from math import ceil, factorial, gcd
import sys
import bisect


sys.setrecursionlimit(10 ** 7)
INF = float("inf")
MOD = 10 ** 9 + 7

si = lambda: input().strip()
ii = lambda: int(input())
mii = lambda: map(int, input().split())
lmii = lambda: list(map(int, input().split()))
smii = lambda: sorted(map(int, input().split()))


N = ii()
S = si()

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 dist in range(N):
        j = i + dist
        k = j + dist
        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:
s=int(input())
t=input()
a=0
b=0
c=0
for i in range(s):
  if t[i]=='R':
    a=a+1
  elif t[i]=='G':
    b=b+1
  else:
    c=c+1
g=a*b*c
for j in range(s):
  for k in range(j+1,s):
    p=2*k-j
    if p>s-1:
      break
    if t[j]!=t[k] and t[p]!=t[k] and t[p]!=t[j]:
      g=g-1
print(g)

Submission status: Accepted

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
import sys,bisect,string,math,time,functools,random
def Golf():*a,=map(int,open(0))
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,Directed=False,index=0):
    org_inp=[];g=[[] for i in range(n)]
    for i in range(E):
        inp=LI();org_inp.append(inp)
        if index==0:inp[0]-=1;inp[1]-=1
        if len(inp)==2:
            a,b=inp;g[a].append(b)
            if not Directed:g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp;aa=(inp[0],inp[2]);bb=(inp[1],inp[2]);g[a].append(bb)
            if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,boundary=1,search=[],replacement_of_found='.',mp_def={'#':1,'.':0}):
#h,w,g,sg=GGI(h,w,boundary=1,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0}) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(k,n=2):return [[tb//(n**bt)%n for bt in range(k)] for tb in range(n**k)]
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)
def show2d(g,h,w):
    for i in range(h):show(g[i*w:i*w+w])

YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
input=lambda: sys.stdin.readline().rstrip()

## return prime factors of N as dictionary {prime p:power of p}
## within 2 sec for N = 2*10**20+7
def primeFactor(N):
    i,n=2,N
    ret={}
    d,sq=2,99
    while i<=sq:
        k=0
        while n%i==0:
            n,k,ret[i]=n//i,k+1,k+1
        if k>0 or i==97:
            sq=int(n**(1/2)+0.5)
        if i<4:
            i=i*2-1
        else:
            i,d=i+d,d^6
    if n>1:
        ret[n]=1
    return ret


## return the list of prime numbers in [2,N], using eratosthenes sieve
## within 2sec for N = 1.2*10**7
def PrimeNumSet(N):
    Max = int(N**0.5)
    seachList = [i for i in range(2,N+1)]
    primeNum = []
    while seachList:
        if seachList[0] <= Max:
            break
        primeNum.append(seachList[0])
        tmp = seachList[0]
        seachList = [i for i in seachList if i % tmp != 0]
    primeNum.extend(seachList)
    return primeNum

## retrun LCM of numbers in list b
## within 2sec for no of B = 10*5  and  Bi < 10**6
def LCM(b,mo=10**9+7):
    prs=PrimeNumSet(max(b))
    M=dict(zip(prs,[0]*len(prs)))
    for i in b:
        dc=primeFactor(i)
        for j,k in dc.items():
            M[j]=max(M[j],k)
    
    r=1
    for j,k in M.items():
        if k!=0:
            r*=pow(j,k,mo)
            r%=mo
    return r

show_flg=False
show_flg=True

'''
#C
g=[[1]*201 for i in range(201)]
for a in range(1,201):
    for b in range(1,201):
        g[a][b]=math.gcd(a,b)

k=I()
ans=0
for a in range(1,k+1):
    for b in range(1,k+1):
        for c in range(1,k+1):
            ans+=g[a][g[b][c]]
         
print(ans)
'''


#D
n=I()
s=input()
A=[[0],[0],[0]]
for i in range(n):
    w=s[i]
    A[0].append(A[0][-1]+(w=='R'))
    A[1].append(A[1][-1]+(w=='G'))
    A[2].append(A[2][-1]+(w=='B'))

#show(A)
t='RGB'

a=0
for i in range(1,n-1):
    w=s[i]
    if w=='R':
        j,k=1,2
    elif w=='G':
        j,k=0,2
    elif w=='B':
        j,k=0,1

    a+=A[j][i]*(A[k][n]-A[k][i])
    a+=A[k][i]*(A[j][n]-A[j][i])
    for l in range(i):
        if i+i-l>=n:
            continue
        if set([s[l],s[i+i-l]])==set([t[j],t[k]]):
            a-=1

print(a)

Submission status: Accepted

Solution code:
n = int(input())
s = list(input())
ans = 0
r = []
g = []
b = []
for i in range(n):
    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)
d = 0
for i in range(n-2):
    for j in range(i,n-1):
        k = j+j-i
        if k < n and s[i] != s[j] and s[k] != s[i] and s[k]!=s[j]:
            d+=1
print(ans-d)

Submission status: Accepted

Solution code:
import collections

def other(a, b):
    if(a!="R" and b!="R"):
        return "R"
    if(a!="G" and b!="G"):
        return "G"
    if(a!="B" and b!="B"):
        return "B"


N = int(input())
S = str(input())
counterList = []

for i in range(N):
    counterList.append(collections.Counter(S[i:]))

result = 0
for j in range(1, N-1):
    for i in range(j):
        if(S[i] != S[j]):
            key = other(S[i], S[j])
            result += counterList[j][key]
            if(2*j-i < N):
                if(S[2*j-i] == key):
                    result -= 1
print(result)

Submission status: Accepted

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

lr = []
lg = []
lb = []

for i in range(n):
    if ln[i] == "R":
        lr.append(i)
    elif ln[i] == "G":
        lg.append(i)
    else:
        lb.append(i)

ans = 0
ba = len(lb)

for i in lr:
    for j in lg:
        ta = ba
        if (i+j) % 2 == 0 and ln[(i+j) // 2] == "B":
            ta -= 1

        d = abs(j - i)
        df = max(j+d, i+d)
        dn = min(j-d, i-d)
        if df < n and ln[df] == "B":
            ta -= 1
        if dn > 0 and ln[dn] == "B":
            ta -= 1
        ans += ta

print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(300000)
from collections import defaultdict
 
def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LMI(): return list(map(int, sys.stdin.readline().split()))
MOD = 10 ** 9 + 7
INF = float('inf')
 
 
N = I()
S = input()

# N = 39
# S = 'RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB'
 
d = defaultdict(int)
for c in S:
    d[c] += 1
plus = d['R'] * d['G'] * d['B']

# print(plus)
 
minus = 0
for j in range(1, N - 1):
    for l in range(1, N):
        i, k = j - l, j + l
        if i < 0 or k > N - 1:
            break
        if S[i] != S[j] and S[j] != S[k] and S[k] != S[i]:
            minus += 1
 
print(plus - minus)

Submission status: Accepted

Solution code:
n=int(input());s=input();c=s.count
print(c('R')*c('G')*c('B')-sum(''.join(sorted(s[i:i+w*2+1:w]))=='BGR'for i in range(n-2)for w in range(1,(n-i+1)//2)))

Submission status: Accepted

Solution code:
N = int(input())
S = input()
X = [0]*3
for s in S:
  if s == "R":
    X[0] += 1
  elif s == "B":
    X[1] += 1
  else:
    X[2] += 1
total = X[0]*X[1]*X[2]
flag = [False] * 3
for i in range(N-2):
  for j in range(i+1, N-1):
    if S[i] == "R":
      flag[0] = True
    elif S[i] == "B":
      flag[1] = True
    else:
      flag[2] = True
    if S[j] == "R":
      flag[0] = True
    elif S[j] == "B":
      flag[1] = True
    else:
      flag[2] = True
    k = j + j - i
    if k <= N-1:
      if S[k] == "R":
        flag[0] = True
      elif S[k] == "B":
        flag[1] = True
      else:
        flag[2] = True
    if all(flag):
      total -= 1
    flag = [False]*3
print(total)

Submission status: Accepted

Solution code:
n = int(input())
s = input()
ans = 0
ans_list = []

R_index = []
G_index = []
B_index = []

for i in range(n):
    if s[i] == 'R':
        R_index.append(i)
    elif s[i] == 'G':
        G_index.append(i)
    elif s[i] == 'B':
        B_index.append(i)

ans = len(R_index) * len(G_index) * len(B_index)

for j in range(1, n-1):
    for i in range(min(n-j-1,j)+1):
        # print(j,i)
        # print(min(n-j-1,j))
        #
        # print(s[j-i],s[j],s[j+i])
        if s[j-i] != s[j] and s[j] != s[j+i] and s[j-i] != s[j+i]:
            # print('here')
            ans -= 1

print(ans)

Submission status: Accepted

Solution code:
from collections import Counter

n = int(input())
s = input()
try:
  x, y, z = Counter(s).values()
  print(x * y * z - sum(s[i] != s[(i + j) // 2] != s[j] != s[i]
                        for i in range(n) for j in range(i + 2, n, 2)))
except ValueError:
  print(0)

Submission status: Accepted

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

for i in range(N):
    if S[i] == 'R':
        A[0].append(i)
    elif S[i] == 'G':
        A[1].append(i)
    else:
        A[2].append(i)
ans = len(A[0])*len(A[1])*len(A[2])
p = 0
for i in range(N):
  for j in range(N):
    if i+j+j <= N-1:
      if S[i] != S[i+j] and S[i] != S[i+j+j] and S[i+j] != S[i+j+j]:
        p += 1

print(ans-p)

Submission status: Accepted

Solution code:
# coding: utf-8
N = int(input())
S = 'D' + input()


rgb_count = [[0 for i in range(3)] for j in range(N+1)]
for i in range(1, N+1):
    if S[i] == 'R':
        rgb_count[1][0] += 1
    elif S[i] == 'G':
        rgb_count[1][1] += 1
    else:
        rgb_count[1][2] += 1


dict={'R':1, 'G':2, 'B':4}
d = ['', 'B', 'G', 'R']
dic = {'R': [1,2], 'G': [0,2], 'B': [0,1]}
ret = rgb_count[1][0]*rgb_count[1][1]*rgb_count[1][2]
for i in range(2,N):
    ran = min([i-1, N-i])
    if ran < 1: continue
    for k in range(1, ran+1):
        if dict[S[i-k]]+dict[S[i]]+dict[S[i+k]] == 7:
            ret -= 1

print(ret)

Submission status: Accepted

Solution code:
N = int(input())
S = input()
ans = 0
r = g = b = rg = rb = gb = 0

for c in S:
    if c=="B":
        ans += rg
        rb += r
        gb += g
        b += 1
    elif c=="G":
        ans += rb
        rg += r
        gb += b
        g += 1
    else:
        ans += gb
        rg += g
        rb += b
        r += 1
for j in range(1, N):
    Sj = S[j]
    for Si, Sk in zip(S[j-1::-1], S[j+1:]):
        if len({Si, Sj, Sk}) == 3:
            ans -= 1
print(ans)

Submission status: Accepted

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

r = [0] * (n)
g = [0] * (n)
b = [0] * (n)
if s[0] == 'R':
  r[0] = 1
elif s[0] == 'G':
  g[0] = 1
else:
  b[0] = 1

for i in range(n-1):
  r[i+1] = r[i]
  g[i+1] = g[i]
  b[i+1] = b[i]
  
  if s[i+1] == 'R':
    r[i+1] += 1
  elif s[i+1] == 'G':
    g[i+1] += 1
  else:
    b[i+1] += 1
    
ans = 0
for i in range(n):
  if s[i] == 'R':
    for j in range(i+1,n):
      if j+1 >= n:
        continue
        
      if s[j] == 'G':
        ans += b[-1] - b[j]
        if j+j-i < n and s[j+j-i] == 'B':
          ans -= 1
          
      if s[j] == 'B':
        ans += g[-1] - g[j]
        if j+j-i < n and s[j+j-i] == 'G':
          ans -= 1        
        
  if s[i] == 'G':
    for j in range(i+1,n):
      if j+1 >= n:
        continue
        
      if s[j] == 'R':
        ans += b[-1] - b[j]
        if j+j-i < n and s[j+j-i] == 'B':
          ans -= 1        
        
      if s[j] == 'B':
        ans += r[-1] - r[j]
        if j+j-i < n and s[j+j-i] == 'R':
          ans -= 1        
        
  if s[i] == 'B':
    for j in range(i+1,n):
      if j+1 >= n:
        continue
        
      if s[j] == 'G':
        ans += r[-1] - r[j]
        if j+j-i < n and s[j+j-i] == 'R':
          ans -= 1        
        
      if s[j] == 'R':
        ans += g[-1] - g[j]
        if j+j-i < n and s[j+j-i] == 'G':
          ans -= 1        

        
print(ans)

Submission status: Accepted

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

count = 0
r = []
g = []
b = []

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

count += len(r)*len(g)*len(b)

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

print(count)

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 j in range(i + 1, N - 1):
        if S[i] != S[j]:
            x = 2 * j - i
            if x < N and S[i] != S[x] and S[x] != S[j]:
                ans -= 1

print(ans)

Submission status: Accepted

Solution code:
from collections import Counter

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

for i in range(n-2):
    for j in range(i+1, n-1):
        w = j - i
        if j+w >= n:
            continue
        if s[i] != s[j] and s[j+w] != s[j] and s[j+w] != s[i]:
            cnt -= 1

print(cnt)

Submission status: Accepted

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

import queue

def main():
     n = int(input())
     s = input()

     r_list = []
     g_list = []
     b_list = []

     ans = 0

     for i in range(n):
          if s[i] == 'R':
               r_list.append(i)
          elif s[i] == 'G':
               g_list.append(i)
          else:
               b_list.append(i)

     for i in range(n):
          if s[i] == 'R':
               ans += check(i, g_list, b_list)

          if s[i] == 'G':
               ans += check(i, r_list, b_list)

          if s[i] == 'B':
               ans += check(i, r_list, g_list)

     print(ans)

def check(spot, first, second):
     ret = 0
     small_first = []
     big_first = []
     small_second = []
     big_second = []

     for f in first:
          if f < spot: small_first.append(spot - f)
          else: big_first.append(f - spot)

     for s in second:
          if s < spot: small_second.append(spot - s)
          else: big_second.append(s - spot)

     return len(small_first) * len(big_second) + len(small_second) * len(big_first) - len(set(small_first) & set(big_second)) - len(set(small_second) & set(big_first))
     
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n = int(input())
s =     input()
if n < 3:
  print(0)
  exit

result = 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 and s[k] != s[i] and s[k] != s[j] and s[j] != s[i]:
      result -= 1

print(result)