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: Time Limit Exceeded

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

import sys
# import math
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product                # product(iter, repeat=n)
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict
from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4


def main():
    mod = 1000000007                  # 10^9+7
    inf = float('inf')
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():  return int(input())
    def mi():  return map(int, input().split())
    def mi_0(): return map(lambda x: int(x)-1, input().split())
    def lmi(): return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():  return list(input())
    
    from itertools import permutations
    n = ii()
    s = input()
    ind_lst = [[] for _ in range(3)]
    d = {'R':0, 'G':1, 'B':2}
    for i, char in enumerate(s):
        ind_lst[d[char]].append(i)
    cnt = 0
    # for perm in permutations([0, 1, 2]):
    #     a, b, c = perm
    #     for x in ind_lst[a]:
    #         i = bisect_left(ind_lst[b], x)
    #         for y in ind_lst[b][i:]:
    #             j = bisect_left(ind_lst[c], y)
    #             for z in ind_lst[c][j:]:
    #                 if x + z != 2 * y:
    #                     cnt += 1
    for x in ind_lst[0]:
        for y in ind_lst[1]:
            for z in ind_lst[2]:
                s, t, u = sorted([x, y, z])
                if s + u != 2 * t:
                    cnt += 1
    print(cnt)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

import sys
# import math
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product                # product(iter, repeat=n)
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict
from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4


def main():
    mod = 1000000007                  # 10^9+7
    inf = float('inf')
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():  return int(input())
    def mi():  return map(int, input().split())
    def mi_0(): return map(lambda x: int(x)-1, input().split())
    def lmi(): return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():  return list(input())
    
    from itertools import permutations
    n = ii()
    s = input()
    ind_lst = [[] for _ in range(3)]
    d = {'R':0, 'G':1, 'B':2}
    for i, char in enumerate(s):
        ind_lst[d[char]].append(i)
    cnt = 0
    for perm in permutations([0, 1, 2]):
        a, b, c = perm
        for x in ind_lst[a]:
            i = bisect_left(ind_lst[b], x)
            for y in ind_lst[b][i:]:
                j = bisect_left(ind_lst[c], y)
                for z in ind_lst[c][j:]:
                    if x + z != 2 * y:
                        cnt += 1
    print(cnt)


    

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

import sys
# import math
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product                # product(iter, repeat=n)
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4


def main():
    mod = 1000000007                  # 10^9+7
    inf = float('inf')
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():  return int(input())
    def mi():  return map(int, input().split())
    def mi_0(): return map(lambda x: int(x)-1, input().split())
    def lmi(): return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():  return list(input())
    
    from itertools import permutations
    n = ii()
    s = input()
    ind_lst = [[] for _ in range(3)]
    d = {'R':0, 'G':1, 'B':2}
    for i, char in enumerate(s):
        ind_lst[d[char]].append(i)
    cnt = 0
    for perm in permutations([0, 1, 2]):
        a, b, c = perm
        for x in ind_lst[a]:
            for y in ind_lst[b]:
                if x < y:
                    for z in ind_lst[c]:
                        if y < z and z - y != y - x:
                            cnt += 1
    print(cnt)


    

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.readline
sys.setrecursionlimit(10 ** 6)


############ ---- Input Functions ---- ############
def in_int():
    return (int(input()))


def in_list():
    return (list(map(int, input().split())))


def in_str():
    s = input()
    return (list(s[:len(s) - 1]))


def in_ints():
    return (map(int, input().split()))


n = in_int()

ss = in_str()
count  = 0
for i in range(n):
    for j in range(i+1,n):
        for k in range(j+1,n):
            if k-j == j-i or ss[k] == ss[j] or ss[k] == ss[i] or ss[i] == ss[j]:
                continue
            else:
                count +=1


print(count)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = input()
cnt = 0
for i in range(n):
        for j in range(i+1,n):
                for k in range(j+1,n):
                    if j - i != k - j and s[i] != s[j] and  s[i] != s[k] and s[j] != s[k]:
                        cnt+=1
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = list(input())
counter = 0
for i in range(n - 2):
  for j in range(i + 1, n - 1):
    for k in range(j + 1, n):
      if ((j - i) != (k - j)):
        if (s[i] != s[j]) & (s[j] != s[k]) & (s[k] != s[i]):
          counter += 1
print(counter)

Submission status: Time Limit Exceeded

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

an = 0

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

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()
total = 0
for i in range(N - 2):
  for j in range(i + 1, N - 1):
    for k in range(j + 1, N):
      if j - i != k - j:
        if S[i] != S[j] and S[j] != S[k] and S[k] != S[i]:
          total += 1
print(total)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()
r = []
g = []
b = []

def greedy(s, l1, l2):
  total = 0
  for i in l1:
    for j in l2:
      if s < i < j:
        if i - s != j - i:
          total += 1
  return total

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

total = 0
for i in range(N):
  if S[i] == 'R':
    total += greedy(i, g, b)
    total += greedy(i, b, g)
  elif S[i] == 'G':
    total += greedy(i, b, r)
    total += greedy(i, r, b)  
  else:
    total += greedy(i, r, g)
    total += greedy(i, g, r)
print(total)

Submission status: Time Limit Exceeded

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

if (n == 1) or (n == 2):
    print(0)
    exit()

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

print(sumnum)

Submission status: Time Limit Exceeded

Solution code:
import math

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

R, G, B = s.count("R"), s.count("G"), s.count("B")
ans = R * G * B

for i in range(n):
    for j in range(n):
        c1 = i
        c2 = i + j
        c3 = i + j * 2
        if c3 >= n: continue
        if c1 == c2 == c3: continue
        if s[c1] != s[c2] and s[c2] != s[c3] and s[c1] != s[c3]:
            ans -= 1

print(ans)
# 012 024 036 048
# 123 135 147 159

Submission status: Time Limit Exceeded

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

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

sum = 0

for i in range(0, N):
    if S[i] == "R":
        R.append(i)
    elif S[i] == "G":
        G.append(i)
    else:
        B.append(i)

for r in range(0, len(R)):
    for g in range(0, len(G)):
        for b in range(0, len(B)):
            if abs(R[r] - G[g]) != abs(G[g] - B[b]) and abs(R[r] - G[g]) != abs(B[b] - R[r]) and abs(G[g] - B[b]) != abs(B[b] - R[r]):
                sum += 1

print(sum)

Submission status: Time Limit Exceeded

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

nr = 0
ng = 0
nb = 0

for i in range(0, N):
    if S[i] == "R":
        nr += 1
    elif S[i] == "G":
        ng += 1
    else:
        nb += 1

count = 0

for i in range(0, N-2):
    for j in range(i+1, N-1):
        k = j + (j - i)
        if k < N and ord(S[i]) + ord(S[j]) + ord(S[k]) == ord("R") + ord("G") + ord("B"):
            count += 1

print(nr*ng*nb - count)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
s=input()
t=0
for i in range(1,n-1):
    for j in range(i+1, n):
        for k in range(j+1,n+1):
            if j*2!=k+i:
                if s[i-1]!=s[j-1] and s[i-1]!=s[k-1] and s[k-1]!=s[j-1]:
                    t+=1
print(t)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline

n = int(input())
s = input() #sys.stdin.readlineは最後が改行

r = [0]*n
g = [0]*n
b = [0]*n

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

from itertools import accumulate
r_nokori = list(reversed(r))
r_nokori = list(reversed(list(accumulate(r_nokori))))
g_nokori = list(reversed(g))
g_nokori = list(reversed(list(accumulate(g_nokori))))
b_nokori = list(reversed(b))
b_nokori = list(reversed(list(accumulate(b_nokori))))

ans = 0

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

        if (s[i]=='R' and s[j]=='G') or (s[i]=='G' and s[j]=='R'):
            ans += b_nokori[j+1]
            if 2*j-i <= n:
                if s[2*j-i] == 'B': ans-= 1

        if (s[i]=='G' and s[j]=='B') or (s[i]=='B' and s[j]=='G'):
            ans += r_nokori[j+1]
            if 2*j-i <= n:
                if s[2*j-i] == 'R': ans-= 1

        if (s[i]=='B' and s[j]=='R') or (s[i]=='R' and s[j]=='B'):
            ans += g_nokori[j+1]
            if 2*j-i <= n:
                if s[2*j-i] == 'G': ans-= 1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()
sum = 0
r = 0
g = 0
b = 0

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

sum = r*g*b

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

print(sum)

Submission status: Time Limit Exceeded

Solution code:
from functools import lru_cache
#@lru_cache(maxsize=1000)
N = int(input())
S =input()
a = 0
for i in range(N-2):
  for j in range(i,N-1):
    for k in range(j,N):
      if S[i] != S[j] and S[i] != S[k] and S[k] != S[j] and j -i != k-j:
        a+= 1
print(a)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = list(input())
r = [i for i, x in enumerate(s) if x == "R"]
g = [i for i, x in enumerate(s) if x == "G"]
b = [i for i, x in enumerate(s) if x == "B"]
ans = len(r) * len(g) * len(b)
if len(b) < len(g):
    g, b = b, g
elif len(b) < len(r):
    r, b = b, r
else:
    pass
for i in r:
    for j in g:
        i_ = min(i, j)
        j_ = max(i, j)
        div = (j_ - i_)
        if i_ - div in b:
            ans -= 1
        if div % 2 == 0:
            k_2 = div // 2 + i_
            if div // 2 + i_ in b:
                ans -= 1
        if div + j_ in b:
            ans -= 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = list(input())
r = [i for i, x in enumerate(s) if x == "R"]
b = [i for i, x in enumerate(s) if x == "B"]
g = [i for i, x in enumerate(s) if x == "G"]
ans = len(r) * len(b) * len(g)
for i in r:
    for j in g:
        i_ = min(i, j)
        j_ = max(i, j)
        div = (j_ - i_)
        if i_ - div in b:
            ans -= 1
        if div % 2 == 0:
            k_2 = div // 2 + i_
            if div // 2 + i_ in b:
                ans -= 1
        if div + j_ in b:
            ans -= 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# correct answer
n = int(input())
s = input()
r = s.count("R")
g = s.count("G")
b = s.count("B")
total = r*g*b
for i in range(n):
    for d in range(n):
        j = i + d
        k = j + d
        if k >= n:
            continue
        if s[i] != s[j] and s[j] != s[k] and s[k] != s[i]:
            total -= 1
print(total)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = input()
s = s.replace('R', '0')
s = s.replace('G', '1')
s = s.replace('B', '2')

s0 = [0] * (n + 5)
s1 = [0] * (n + 5)
s2 = [0] * (n + 5)

for i in range(n):
    s0[i + 1] = s0[i] + (s[i] == '0')
    s1[i + 1] = s1[i] + (s[i] == '1')
    s2[i + 1] = s2[i] + (s[i] == '2')

#print(s0)
#print(s1)
#print(s2)

ans = 0
for i in range(n):
    for j in range(i + 1, n):
        if s[i] == s[j]: continue
        h = 99 - (ord(s[i]) + ord(s[j]))
        if h == 0:
            ans += s0[n] - s0[j]
            if 2 * j - i < n and s[2 * j - i] == '0': ans -= 1
        if h == 1:
            ans += s1[n] - s1[j]
            if 2 * j - i < n and s[2 * j - i] == '1': ans -= 1
        if h == 2:
            ans += s2[n] - s2[j]
            if 2 * j - i < n and s[2 * j - i] == '2': ans -= 1
        #print(i, j, h, ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations as pm

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

    red = [0 for i in range(n+1)]
    green = [0 for i in range(n+1)]
    blue = [0 for i in range(n+1)]

    for i in range(2,n+1):
        if s[i-2]=='R':
            red[i] = red[i-1] + 1
        else:
            red[i] = red[i-1]
        if s[i-2]=='G':
            green[i] = green[i-1] + 1
        else:
            green[i] = green[i-1]
        if s[i-2]=='B':
            blue[i] = blue[i-1] + 1
        else:
            blue[i] = blue[i-1]
    # red[n] = red[n-1]
    # green[n] = green[n-1]
    # blue[n] = blue[n-1]

    # print(red)
    # print(blue)
    # print(green)


    ans = 0
    for i in range(1,n+1):
        for j in range(i+2,n+1):

            for a,b,c in pm("RGB"):
                if s[i-1]==a and s[j-1]==c:
                    if b =="R":
                        ans += red[j] - red[i+1]
                    elif b=="G":
                        ans += green[j] - green[i+1]
                    elif b == "B":
                        ans += blue[j] - blue[i+1]
                    
                    if (j-i)%2==0 and s[(j-i)//2+i-1] == b:
                        ans -= 1
                    # print(i,j,b,ans)
    print(ans)

if __name__== "__main__":
    main()

Submission status: Time Limit Exceeded

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

counter = 0
for i in range(n-2):
  for j in range(i+1, n-1):
    if s[i] == s[j]:
      continue
    for k in range(j+1, n):
      if s[i] == s[k] or s[j] == s[k] or (j - i) == (k - j):
        continue
      else:
        counter += 1
          
print(counter)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = list(input())
dp = [0,0,0]
for i in range(0,N):
	dp[0]=S[i]
	for j in range(i+1,N):
		if dp[0]!=S[j]:
			dp[1]=S[j]
			for k in range(j+1,N):
				if dp[0]!=dp[1] and dp[1]!=S[k] and dp[0]!=S[k] and j-i!=k-j :
					dp[2]+=1
print(dp[2])

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = str(input())
"""
全体で一つ目の条件を満たす組み合わせはrgb
2個目の条件を見るにはr,gの位置を固定したときにbが3つが等間隔になるように並ばないことを確認すればいい
"""
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)
cnt = len(r)*len(g)*len(b)
for i in r:
    for j in g:
        if (i+j)/2 in b:
            cnt = cnt -1
        if (abs(i-j) + max(i,j)) in b:
            cnt = cnt -1
        if (min(i,j) - abs(i-j)) in b:
            cnt = cnt -1

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
s = input()
count = 0
for i in range(n):
    for j in range(i, n):
        if s[i] != s[j]:
            for k in range(j, n):
                if s[i] != s[k] and s[j] != s[k] and (j-i) != (k-j):
                    count += 1
print(count)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()
sum = 0
r = 0
g = 0
b = 0

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

sum = r*g*b

for i in range(N):
    for j in range(N//2 +1):
        try:
            a = S[i]
            b = S[i+j]
            c = S[i+2*j]
            if a!=b and b!=c and c!=a:
                sum -= 1
        except:
            continue

print(sum)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = input()
sum = 0
r = 0
g = 0
b = 0

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

sum = r*g*b

for i in range(N):
    for j in range(N):
        try:
            a = S[i]
            b = S[i+j]
            c = S[i+2*j]
            if a!=b and b!=c and c!=a:
                sum -= 1
        except:
            continue

print(sum)

Submission status: Time Limit Exceeded

Solution code:
num=int(input())
str=input()
ans=0

for i in range(num):
    for j in range(i+1,num):
        for k in range(j+1,num):
            if (str[i]!=str[j] and str[j]!=str[k] and str[i]!=str[k]) and (j-i!=k-j):
                ans+=1
                
print(ans)

Submission status: Time Limit Exceeded

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

for i in range(N):
    for j in range(i+1,N):
        a = S[i]
        b = S[j]
        if a == b:
            continue
        for k in range(j+1,N):
            c = S[k]
            if a!=c and b!=c and j-i!=k-j:
                sum += 1

print(sum)

Submission status: Time Limit Exceeded

Solution code:
def checkRGB(a,b,c):
    if a == b or b == c or c == a:
        return 0
    else:
        return 1

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

if N<4:
    print(0)
    exit()
sum1 = S.count("R")*S.count("G")*S.count("B")
sum2 = 0
for i in range(1,N):
    center = S[i]
    for j in range(i):
        left = S[j]
        if 2*i-j<N:
            right = S[2*i-j]
            sum2 +=  checkRGB(left,center,right)

print(sum1-sum2)

Submission status: Time Limit Exceeded

Solution code:
def checkRGB(a,b,c):
    if a == b or b == c or c == a:
        return False
    else:
        return True

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

if N<4:
    print(0)
    exit()
sum = S.count("R")*S.count("G")*S.count("B")
for i in range(1,N):
    center = S[i]
    for j in range(i):
        left = S[j]
        if 2*i-j<N:
            right = S[2*i-j]
            if checkRGB(left,center,right):
                sum -= 1

print(sum)

Submission status: Time Limit Exceeded

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

dic = {"R":[], "G":[], "B":[]}

for i in range(n):
  dic[S[i]].append(i)

lr = len(dic["R"])
lg = len(dic["G"])
lb = len(dic["B"])
y = lr*lg*lb

for i in range(lr):
  for j in range(lg):
    for k in range(lb):
      r = dic["R"][i]
      g = dic["G"][j]
      b = dic["B"][k]
      if abs(r - g) == abs(r - b):
        y -= 1
      elif abs(g - r) == abs(g - b):
        y -= 1
      elif abs(b - r) == abs(b - g):
        y -= 1
        

print(y)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
s=input()
R=[0]
G=[0]
B=[0]
ans=0
#RGBの累積和を作る
for i in range(N):
  if s[i]=="R":
    R[i]+=1
  elif s[i]=="G":
    G[i]+=1
  else:
    B[i]+=1
  R.append(R[i])
  G.append(G[i])
  B.append(B[i])
del R[-1]
del G[-1]
del B[-1]
#作った
 
#全探索する
for i in range(N-2):
  a=s[i]
  for j in range(i+1,N-1):
    if a==s[j]:
      continue
    b=s[j]
    k=2*j-i
    if "R" not in a+b:
      ans+=R[-1]-R[j]
      if k>=N:
        continue
      if s[k]=="R":
        ans-=1
    
    if "G" not in a+b:
      ans+=G[-1]-G[j]
      if k>=N:
        continue
      if s[k]=="G":
        ans-=1

    if "B" not in a+b:
      ans+=B[-1]-B[j]
      if k>=N:
        continue
      if s[k]=="B":
        ans-=1
print(ans)

Submission status: Time Limit Exceeded

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

pattern = [[i,j,k] for i in range(N) 
           for j in range(N) 
           for k in range(N) 
           if i < j and j < k 
           and j-i != k-j 
           and S[i] != S[j] and S[j] != S[k] and S[i] != S[k]]

count = len(pattern)
print(count)

Submission status: Time Limit Exceeded

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-2):
  a=s[i]
  for j in range(i+1,N-1):
    if a==s[j]:
      continue
    b=s[j]
    k=2*j-i
    if "R" not in a+b:
      try:
        if s[k]=="R":
          ans-=1
      except:
        pass
      
    if "G" not in a+b:
      try:
        if s[k]=="G":
          ans-=1
      except:
        pass
      
    if "B" not in a+b:
      try:
        if s[k]=="B":
          ans-=1
      except:
        pass

print(ans)

Submission status: Time Limit Exceeded

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

pattern = [[i,j,k] for i in range(N) for j in range(N) for k in range(N) if i < j and j < k and j-i != k-j]

count = 0

for a in pattern:
    if S[a[0]] != S[a[1]] and S[a[1]] != S[a[2]] and S[a[0]] != S[a[2]]:
        count = count + 1

print(count)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
s=input()
R=[0]
G=[0]
B=[0]
ans=0
#RGBの累積和を作る
for i in range(N):
  if s[i]=="R":
    R[i]+=1
  elif s[i]=="G":
    G[i]+=1
  else:
    B[i]+=1
  R.append(R[i])
  G.append(G[i])
  B.append(B[i])
del R[-1]
del G[-1]
del B[-1]
#作った

#全探索する
for i in range(N-2):
  a=s[i]
  for j in range(i+1,N-1):
    if a==s[j]:
      continue
    b=s[j]
    k=2*j-i
    if "R" not in a+b:
      ans+=R[-1]-R[j]
      try:
        if s[k]=="R":
          ans-=1
      except:
        pass
    
    if "G" not in a+b:
      ans+=G[-1]-G[j]
      try:
        if s[k]=="G":
          ans-=1
      except:
        pass
        
    if "B" not in a+b:
      ans+=B[-1]-B[j]
      try:
        if s[k]=="B":
          ans-=1
      except:
        pass
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import accumulate
N=int(input())
s=input()
R=[]
G=[]
B=[]
ans=0
#RGBの累積和を作る
for i in range(N):
  if s[i]=="R":
    R.append(1)
    G.append(0)
    B.append(0)
  elif s[i]=="G":
    G.append(1)
    R.append(0)
    B.append(0)
  else:
    B.append(1)
    G.append(0)
    R.append(0)
R=list(accumulate(R))
G=list(accumulate(G))
B=list(accumulate(B))
#作った

#全探索する
for i in range(N-2):
  a=s[i]
  for j in range(i+1,N-1):
    if a==s[j]:
      continue
    b=s[j]
    k=2*j-i
    if "R" not in a+b:
      ans+=R[-1]-R[j]
      try:
        if s[k]=="R":
          ans-=1
      except:
        pass
    
    if "G" not in a+b:
      ans+=G[-1]-G[j]
      try:
        if s[k]=="G":
          ans-=1
      except:
        pass
        
    if "B" not in a+b:
      ans+=B[-1]-B[j]
      try:
        if s[k]=="B":
          ans-=1
      except:
        pass
print(ans)

Submission status: Time Limit Exceeded

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

count = 0

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

print(count)

Submission status: Time Limit Exceeded

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

# 大きく求めて引く
ans = S.count("R") * S.count("G") * S.count("B")

for i in range(N-2):
    for k in range(i+2, N):
        if (i+k) % 2 == 0 and set([S[i], S[(i+k)//2], S[k]]) == set(["R", "G", "B"]):
            ans -= 1

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys

def solve():
    input = sys.stdin.readline
    N = int(input())
    S = input().strip("\n")
    toInt = {"R": 0, "G":1, "B": 2}
    count = [[0, 0, 0] for _ in range(N)]
    count[N-1][toInt[S[N-1]]] += 1
    for i in reversed(range(N-1)):
        for j in range(3): count[i][j] = count[i+1][j]
        count[i][toInt[S[i]]] += 1

    ans = 0
    for i in range(N-2):
        iInt = toInt[S[i]]
        for j in range(i+1, N-1):
            right = {0, 1, 2} - {iInt, toInt[S[j]]}
            if len(right) == 1:
                for key in right:
                    ans += count[j + 1][key]
                    if 2 * j - i < N and toInt[S[2*j - i]] == key: ans -= 1
    print(ans)

    return 0

if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

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

for i in range(n):
    for j in range(n):
        for k in range(n):
            if not (i<j<k):
                continue
            if (s[i]!=s[j])&(s[j]!=s[k])&(s[k]!=s[i])&(j-i!=k-j):
                sum+=1

print(sum)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
from bisect import bisect_left
n = int(input())
s = input()
c = 0
f = defaultdict(list)
for i in range(n):
	f[s[i]].append(i)
for i in range(n):
	for j in range(i+1, n):
		if  s[i] != s[j]:
			for k in f:
				if k != s[i] and k != s[j]:
					t = bisect_left(f[k], j+1)
					t1 = bisect_left(f[k][t:], 2*j - i)
					try:
						if f[k][t:][t1] == 2*j - i:
							c += len(f[k][t:]) - 1	
						else:
							c += len(f[k][t:])
					except:
						c += len(f[k][t:])
print(c)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
s=list(input())
c=0
for i in range(1,n+1):
    for j in range(i+1,n+1):
        if s[i-1]==s[j-1]:
            continue
        for k in range(j+1,n+1):
            if s[k-1]!=s[j-1] and s[i-1]!=s[k-1]:
                if j-i != k-j:
                    c+=1
print(c)