We are to count triples (i, j, k) with 1 <= i < j < k <= N such that:
- All three characters are distinct (i.e., S_i, S_j, S_k are all different; they are from {R,G,B} so that means they are a permutation of the three colors).
- The distances are not equal: j - i != k - j (i.e., the triple is not an arithmetic progression with equal steps).
We have N up to 4000, so O(N^2) is feasible (16 million). O(N^3) would be too big (64e9). We need an efficient counting.
We want to count all triples with distinct colors, then subtract those that are also arithmetic progressions (equal step) because condition2 is "not equal". Actually we want triples that satisfy both conditions, so count all triples with distinct colors minus those that also have j-i = k-j. However careful: Condition2 says j-i != k-j. So we want those distinct-color triples that are NOT arithmetic progressions (with equal step). So total valid = (# of triples with all colors distinct) - (# of triples with all colors distinct AND j-i = k-j). That's a straightforward approach if we can compute both.
Let total_distinct = number of triples (i<j<k) where S_i,S_j,S_k all different. Since there are only three colors, we can compute it as total number of triples C(N,3) minus those where at least two are same. But easier: For each combination of three distinct colors, count number of triples with that exact set. Since there are 3 colors, the number of triples with all distinct = sum_{c1<c2<c3} count_i for c1 * count_j for c2 * count_k for c3? But careful: The positions matter and need ordering. Actually we need to count ordered triples with i<j<k such that the multiset of colors is exactly {R,G,B}. That is equivalent to: for each triple of indices, the colors are distinct if and only if they are all different. So we can count by: total_distinct = total triples - triples where two or three are same (but three same also implies two same; but we can count exactly the complement: triples with at least two equal). Since three distinct is easier? Possibly count directly: For each i, for each j>i, and then count number of k>j such that S_k is the color different from both S_i and S_j, provided S_i != S_j. That leads to O(N^2) if we precompute suffix counts per color. That yields total_distinct easily in O(N^2). With N=4000, O(N^2)=16M is fine. But then we also need to subtract the "bad" ones: those with distinct colors and equal step.
Alternatively, we can directly count the valid triples that meet both conditions in one pass, but subtraction is easier.
So main challenge: Count number of triples (i<j<k) such that:
- S_i, S_j, S_k all distinct.
- j-i = k-j (i.e., k = 2j - i, and i < j < k).
This is a much smaller set because it requires k determined by i and j, so O(N^2) enumeration of (i,j) and check if k=2j-i <= N, and if colors distinct.
We can just loop i from 1 to N, j from i+1 to N, compute k=2*j - i, if k <= N and k > j, then check distinctness condition. That's O(N^2). For N=4000, maximum j up to 4000, i up to j-1, total pairs about 8e6 (actually sum_{j=2}^{N} (j-1) = N(N-1)/2 ~ 8 million for N=4000). That's fine.
Thus answer = total_distinct - count_bad.
Now compute total_distinct: Option 1: O(N^2) loop over ij that have color different from both. For each i<j, if S_i != S_j, then we want count of k>j with S_k != S_i and S_k != S_j, i.e., the third color. Since there are exactly three colors, the third color is uniquely determined. So we can precompute suffix counts: for each position p, we can have counts of R,G,B from p to N. Then for pair (i,j) with different colors, the number of valid k > j is suffix_count[j+1][third_color]. This can be computed in O(N^2) total. But O(N^2) is fine.
Alternatively, we can compute total_distinct by combinatorial counting: count all triples with colors all distinct = total triples - triples with at least two same. Compute total triples = C(N,3). Compute triples with at least two same: Count those where exactly two are same and one different? Since three same also has two same. Let's compute: For each color c, choose 2 positions of that color and 1 of another? That would double count triples with three of the same? Actually three same has three pairs of two same but when counting "two same" we need to include or exclude carefully. But maybe easier to compute total_distinct by enumeration of pairs (i,j) as above. That ensures we get exact number. I'd go with enumeration of pairs.
But careful: In the enumeration for total_distinct: for each i from 1 to N, for each j from i+1 to N, if S_i != S_j then add suffix_count[j+1][third_color]. The third_color is the one not in {S_i,S_j}. This sum yields exactly the number of triples (i,j,k) with i<j<k and distinct colors. Let's verify: each triple (i,j,k) will be counted exactly once when i and j are the first two indices; and condition S_i != S_j ensures we only count if they are different, then if S_k is the third color we count it. Yes.
Now compute suffix_counts: Let's index from 0-based or 1-based? Implementation can be 0-indexed. We'll define array of length N. For each position pos from 0 to N-1, we can have suffix counts from pos to end. We'll compute an array suff[pos][c] where c in 0,1,2 representing counts of each color from pos to N-1 inclusive. Then for pair (i,j) with i<j, the valid k are those > j, i.e., positions starting at j+1. So third_color = the missing color. Then add suff[j+1][third_color]. That works.
Alternatively, we can precompute prefix counts and use total counts minus prefix counts to get suffix counts, but suffix array is fine.
Now count_bad: Loop over i from 0 to N-3? Actually we need i<j<k such that k = 2j - i, and distinct colors. So we can for i from 0 to N-1, for j from i+1 to N-1, compute k = 2*j - i. If k < N and k > j, then check if S_i, S_j, S_k all distinct. If yes, then this triple is a bad one (we will subtract). Note: we must ensure k is integer, it always is. So count_bad++.
We need to careful about overflow: number of triples up to C(4000,3) ≈ 400039993998/6 ≈ (64e9)/6 ≈ 10.6e9? Actually 4000^3/6 ≈ 64e9/6 ≈ 10.7e9, which is about 1.07e10, fits in 64-bit (2^63-1 ≈ 9.22e18) so safe. But Python int is arbitrary precision anyway.
But we might sum up to 10e9, but our algorithm O(N^2) will produce that count via loops that add potentially large numbers. We just need to be careful that we use Python's int.
Thus algorithm:
- Read N, S.
- Convert S to list of numbers: e.g., 0 for R, 1 for G, 2 for B.
- Compute suffix counts: suff[pos][c] for pos from N down to 0 (N+1 array where suff[N] = [0,0,0] and for pos from N-1 down to 0: copy from pos+1 and increment color at pos). So suff[pos] = counts from pos to N-1 inclusive.
- total_distinct = 0
- For i in range(N):
for j in range(i+1, N):
if S[i] != S[j]:
third = 3 - S[i] - S[j] # if colors are 0,1,2 then third = 3 - a - b
total_distinct += suff[j+1][third]
- bad = 0
- For i in range(N):
for j in range(i+1, N):
k = 2*j - i
if k < N and k > j:
if S[i] != S[j] and S[j] != S[k] and S[i] != S[k]:
# Actually all distinct condition, but we only need those that also are distinct (they are bad for subtraction only if they are also distinct? Wait: In subtraction, we subtract from total_distinct only the bad ones that are distinct and arithmetic progression. So we must count only those that have distinct colors. So condition: S_i, S_j, S_k all distinct. So check that.
# However, it's possible that arithmetic progression triple has colors not all distinct, but we don't subtract those because total_distinct does not include them. So only subtract those that satisfy distinctness. So we check distinctness.
if S[i] != S[j] and S[j] != S[k] and S[i] != S[k]:
bad += 1
- answer = total_distinct - bad
- print(answer)
Check with examples.
Example1: N=4, S=RRGB. Indices 0:R,1:R,2:G,3:B.
Compute suffix:
suff[4]=[0,0,0]
suff[3]: pos3 B -> [0,0,1]? Actually mapping: let's map: R=0,G=1,B=2.
suff[3] = after inc B: [0,0,1]
suff[2]: pos2 G -> [0,1,1]
suff[1]: pos1 R -> [1,1,1]
suff[0]: pos0 R -> [2,1,1]
Now compute total_distinct:
i=0 (R), j=1 (R): same -> skip.
i=0, j=2 (G): different, third = 3-0-1=2 (B). suff[3][2] = 1 (since suff[3] = [0,0,1]) -> add 1.
i=0, j=3 (B): diff, third = 3-0-2=1 (G). suff[4][1] = 0 -> add 0.
i=1 (R), j=2 (G): diff, third=2 (B). suff[3][2]=1 -> add 1.
i=1, j=3 (B): diff, third=1 (G). suff[4][1]=0 -> add 0.
i=2 (G), j=3 (B): diff, third=0 (R). suff[4][0]=0 -> add 0.
total_distinct = 2.
Now bad:
i=0, j=1: k=2 -> k=2 (since 21-0=2). k=2 > j? 2>1 yes. Check indices: (0,1,2): R,R,G -> not all distinct, skip.
i=0, j=2: k=4 -> out of range.
i=0, j=3: k=6 out.
i=1, j=2: k=3 (22-1=3). k=3 in range, >j. (1,2,3): R,G,B -> all distinct! So bad=1.
i=1, j=3: k=5 out.
i=2, j=3: k=4 out.
bad=1.
Answer = 2-1 =1. matches.
Second example: output 1800. We'll trust.
Complexities: O(N^2) loops for total_distinct and for bad each O(N^2). That's about 2*8e6 = 16e6 operations, plus precomputation O(N). That's fine.
Potential improvements: Could combine loops to compute total_distinct differently to reduce constant, but not needed.
But wait, there is nuance: In total_distinct, we add suffix counts for third color. However, if we later subtract bad ones, we must ensure that the bad ones are indeed counted in total_distinct. Since bad ones are a subset of total_distinct (by definition), this subtraction works.
Thus answer is correct.
But one more nuance: The condition j - i != k - j. In subtraction we subtract only those with j-i = k-j. But what about triples where j-i = k-j but not distinct? They are not in total_distinct, so we don't subtract them. So fine.
Edge cases: N<3, then total_distinct=0, bad=0, answer=0.
Implementation details: Represent colors as integers. Use ord mapping: e.g., if char == 'R' -> 0, 'G' -> 1, 'B' -> 2. Then third = 3 - a - b works because sum of three distinct numbers from {0,1,2} is 0+1+2=3, so third = 3 - a - b. Actually if a and b are distinct, then the missing number is 3 - a - b. Indeed, if a=0,b=1 => third=2; a=0,b=2=> third=1; a=1,b=2=> third=0.
Suffix array: suff = [[0,0,0] for _ in range(N+1)]. For p from N-1 down to 0: suff[p] = suff[p+1].copy(); then suff[p][color[p]] += 1. But copying each time O(N*3) maybe okay but we can do it more efficiently: we can fill in place. Actually we can allocate a list of N+1 lists and compute backwards by incrementing. For p from N-1 down to 0: copy from p+1 to p. However copying list of 3 ints is cheap. Alternatively, we can maintain a running counts and assign to suff[p] as a tuple? Let's just do straightforward: suff = [[0]3 for _ in range(N+1)]; then for i in range(N-1,-1,-1): for c in range(3): suff[i][c] = suff[i+1][c]; suff[i][color[i]] += 1. That's O(N3). Good.
Now total_distinct: Two nested loops: i 0..N-2, j i+1..N-1. For each, if col[i]!=col[j]: third = 3 - col[i] - col[j]; total_distinct += suff[j+1][third]. This yields correct.
Now bad: for i in range(N-2): (since j>i and k>j; i can go up to N-3? Actually i can be up to N-3 because j at least i+1, k=2j-i <= N-1 => 2j - i < N => i > 2j - N, but we can just loop all i, j and check condition k<N.) So for i in range(N): for j in range(i+1, N): k = 2*j - i; if k < N and k > j: then check distinctness. Note: k may be equal to j? If i=j? not possible. Since j>i, k = 2j-i > 2j-j = j, so k>j automatically. But if k==j? Not possible. So condition k>j is automatically satisfied if k integer? Actually since j>i, 2j-i > 2j - (j-1) = j+1? Let's check: if i = j-1, then k = 2j - (j-1) = j+1 > j. So yes, k>j always when i<j. So we just need k<N. So we can just check k < N. But careful: if k == j? Not possible. So we can just check if k < N.
Thus bad loop: for i in range(N): for j in range(i+1, N): k = 2*j - i; if k < N: then check distinctness.
But note: This includes cases where k may equal j? Let's double-check: For k = 2j - i. Since i < j, let j = i + d, d >=1. Then k = 2(i+d) - i = i + 2d. So k = i+2d > i+d = j. So always > j. So fine.
Thus we can simply check if k < N.
Now check that we only count each triple once. Indeed, each triple (i,j,k) with j-i = k-j corresponds to exactly one (i,j) such that k=2j-i. So enumeration over (i,j) yields each bad triple exactly once.
Now answer = total_distinct - bad.
But is there any nuance about the condition j - i != k - j? Yes.
Thus algorithm solves problem.
However, could there be an issue with large memory for suffix? suff is (N+1) x 3 = 4001*3 ~12k ints, trivial.
Time: loops ~ N(N-1)/2 ≈ 8e6 per loop, plus each iteration simple operations. Python should handle within time (since 8e6 * 2 = 16e6, plus overhead of Python loops, might be borderline but typically 4000^2 = 16 million, but we have two loops each about 8 million? Actually the total number of (i,j) pairs is N*(N-1)/2 ≈ 8 million for N=4000. So total_distinct loop does about 8 million iterations, each doing a few operations, which is fine (maybe 0.1-0.2 seconds). The bad loop also does 8 million iterations, similar. So total ~16 million iterations, well within limits for Python (likely < 1 second if optimized; but worst-case 2 seconds? Usually fine for AtCoder's 2 sec? AtCoder typical Python limit is 2 seconds, but 16 million integer operations might be okay if not too heavy. However we should be careful with Python overhead of nested loops: for i in range(N): for j in range(i+1,N): ... That's about 8M iterations, each with a condition and maybe array access. It should be okay, but we can micro-opt by using local variables, avoid function calls, etc.
But note: N max 4000, N(N-1)/2 = 7,998,000 ≈ 8e6. Two loops = 16e6. Python can handle 16 million simple operations within 1 second? Possibly more like 0.3-0.5 sec per 10 million? Actually typical Python can do ~50 million simple operations per second? That's not accurate; depends. But many AtCoder problems with N=2000 and O(N^2) pass; with N=4000 O(N^2) sometimes passes if optimized (e.g., using PyPy). Since we have two O(N^2) loops, it might be okay. However we can also combine the two loops to compute both total_distinct and bad in one pass to reduce overhead? Could be done but not necessary.
We also have suffix precomputation.
Thus solution is straightforward.
But wait: There's potential to compute total_distinct more efficiently using combinatorics to avoid O(N^2) loop? But then we still need the O(N^2) loop for bad? Actually we need O(N^2) for bad anyway; we could compute total_distinct in O(N^2) also, but maybe we could compute total_distinct in O(N) using counts of each color, but then we need to subtract triples where two are same etc. That would be O(N). Then only bad loop O(N^2). That might be more efficient. But is total_distinct easily computable in O(N)? Let's think: number of triples with distinct colors: Since colors are only 3, we can compute as sum over all unordered color sets? Actually we can compute as total number of ways to pick one position for each color: choose i for R, j for G, k for B with i<j<k. But this is not just product of counts because ordering matters. However we can compute by iterating j as middle index? There is known combinatorial formula: Count of ordered triples i<j<k with colors distinct = sum over positions j of (number of R before j)(number of B after j) + (R before)(G after) + ... Actually we can count all triples where middle is j? Not exactly because the colors can be in any permutation. But we can sum over all j as the middle index, and consider the possible colors for i,k relative to j. Since there are 3 colors, for each j we can count triples where i<j<k and colors all distinct. That would be O(N) if we maintain prefix counts. Let's analyze:
For each position j (1-indexed), we want number of ij such that S_i, S_j, S_k are all distinct. For a fixed j, with color c = S_j, the pairs (i,k) must consist of the other two colors, and i must be before j, k after j. The number of ways = (prefix count of color a before j) * (suffix count of color b after j) + (prefix count of color b before j) * (suffix count of color a after j) where {a,b} are the two colors not equal to c. Since colors are distinct, either i has color a and k has color b, or i has color b and k has color a. So total for that j is: pre[a][j-1] * suf[b][j+1] + pre[b][j-1] * suf[a][j+1]. Summing over j gives total distinct triples. And that's O(N) after precomputing prefix and suffix counts. That seems more efficient.
But we already have O(N^2) for bad anyway, so total O(N^2) is fine. However O(N^2) for total_distinct might be acceptable, but if we can replace with O(N) it reduces constant factor. Not necessary but can be a micro-optimization.
Given that N=4000, O(N^2) loops twice is okay. But there is a catch: In my earlier O(N^2) method for total_distinct, we are iterating over i and j and for each we access suffix counts. That is 8e6 operations, which is similar to the bad loop. So total ~16e6. The O(N) method would be ~4000 operations for total_distinct, so total ~8e6 + 4000 ≈ 8e6. That's roughly half the number of loops. Could help with Python speed but likely not critical.
But wait: In the O(N^2) method we also need to compute suffix counts and then loops. The O(N) method also requires prefix and suffix counts. So it's straightforward.
Let's compute using O(N) method:
- pre[pos][c] = counts of color c from 0 to pos-1 (i.e., up to index pos-1). Usually we make an array of size N+1: pre[0] = [0,0,0]; for i from 0 to N-1: pre[i+1] = pre[i].copy(); pre[i+1][color[i]] +=1.
- Similarly suff[pos][c] = counts from pos to N-1. We can compute as before.
Then for each j from 0 to N-1 (middle index), let c = col[j]. Let other1, other2 be the two colors not equal to c. Then ways = pre[j][other1] * suff[j+1][other2] + pre[j][other2] * suff[j+1][other1]. Sum over j gives total_distinct.
But careful: Does this count each triple exactly once? In a triple (i,j,k) with i<j<k, the middle index is j, so it is counted exactly once when iterating over j. Yes. So total_distinct = sum_{j=0}^{N-1} f(j).
We must ensure that i and k are on opposite sides and distinct colors. This formula counts both orders of assignment of the two other colors to i and k. So correct.
Now check with example: N=4, S=0,0,1,2.
Pre:
pre[0]=[0,0,0]
j=0 (col0=0): pre[0]=[0,0,0], suff[1] = counts from index1 to3: col1=0,col2=1,col3=2 => suff[1]=[1,1,1]? Actually compute: suff[1] from earlier: [1,1,1]? Let's compute: suff[1] after manual: index1=0, index2=1, index3=2 => counts: R=1,G=1,B=1. So for j=0, c=0, other colors {1,2}. ways = pre[0][1]suff[1][2] + pre[0][2]suff[1][1] = 01 + 01 = 0.
j=1 (col=0): pre[1]=[1,0,0] (since index0 is R). suff[2] = counts from index2,3: col2=1,col3=2 => [0,1,1]? Actually R:0, G:1, B:1 => yes. ways = pre[1][1]suff[2][2] + pre[1][2]suff[2][1] = 01 + 01 =0.
j=2 (col=1): pre[2] = [1,1,0]? Actually index0 R, index1 R => R=2? Wait pre[2] counts from indices 0,1: both R => [2,0,0]? Let's compute properly: pre[0]=[0,0,0]; after index0 (R): pre[1]=[1,0,0]; after index1 (R): pre[2]=[2,0,0]; after index2 (G): pre[3]=[2,1,0]; after index3 (B): pre[4]=[2,1,1]. So pre[2]=[2,0,0]; suff[3] = counts from index3: [0,0,1]? Actually index3 B => suff[3]=[0,0,1]; but careful: suff[3] = from index3 to end inclusive => B => [0,0,1]; suff[2] = from index2 to 3 => [0,1,1]. For j=2, we need suff[j+1]=suff[3] = [0,0,1]. pre[2]=[2,0,0]. c=1 (G), other colors {0,2}. ways = pre[2][0]suff[3][2] + pre[2][2]suff[3][0] = 21 + 00 = 2. That counts triples with j=2, i before with color R (0) and k after with B (2). That gives 2 triples: i=0,k=3 and i=1,k=3. Indeed both are (0,2,3) and (1,2,3). Note: (0,2,3): R,G,B distinct, and (1,2,3): R,G,B distinct. So that accounts for 2 triples. j=3 (col=2): pre[3]=[2,1,0]; suff[4]=[0,0,0]; other colors {0,1}: ways = pre[3][0]suff[4][1] + pre[3][1]suff[4][0] = 20 + 10 = 0. Total distinct = 2. That matches earlier. So O(N) method works.
Thus we can compute total_distinct efficiently.
Now we only have one O(N^2) loop for bad. That's good.
We need to be careful about indexing: When computing prefix: pre[i] is counts before index i (i.e., positions 0..i-1). So for middle index j, we use pre[j] (counts before j) and suff[j+1] (counts after j). This is fine.
Implementation steps:
- Read N, S.
- Map colors: maybe use dictionary or if-else to assign 0,1,2.
- Build col list.
- Compute pre: list of N+1 arrays of length 3. Initialize pre[0] = [0,0,0]. For i from 0 to N-1: pre[i+1] = pre[i].copy(); pre[i+1][col[i]] += 1.
- Compute suff: list of N+1 arrays. Initialize suff[N] = [0,0,0]. For i from N-1 down to 0: suff[i] = suff[i+1].copy(); suff[i][col[i]] += 1.
- Compute total_distinct = 0. For j in range(N): c = col[j]; other = [0,1,2] excluding c. Let a,b = others (two numbers). total_distinct += pre[j][a] * suff[j+1][b] + pre[j][b] * suff[j+1][a].
Since we only have 3 colors, we can compute explicitly:
if c == 0: total += pre[j][1] * suff[j+1][2] + pre[j][2] * suff[j+1][1]
elif c == 1: total += pre[j][0] * suff[j+1][2] + pre[j][2] * suff[j+1][0]
else: total += pre[j][0] * suff[j+1][1] + pre[j][1] * suff[j+1][0]
- Compute bad = 0. Loop i in range(N): for j in range(i+1, N): k = 2j - i; if k < N: if col[i] != col[j] and col[j] != col[k] and col[i] != col[k]: bad += 1. (Or using distinctness condition: col[i], col[j], col[k] are all different.)
But note: we can optimize by early continue: if col[i]==col[j] then skip because distinctness fails; but we still need to check k? Actually if col[i]==col[j], then triple can't be all distinct, so we don't need to check further. So we can write:
if col[i] != col[j]:
k = 2j - i
if k < N:
if col[i] != col[k] and col[j] != col[k]:
bad += 1
However we also need to ensure col[j]!=col[k] and col[i]!=col[k]; but if col[i]!=col[j] and we ensure col[i]!=col[k] and col[j]!=col[k] then all distinct. So check both.
This avoids computing k when col[i]==col[j], saving some time maybe.
But the loop over i,j is 8M, and the condition col[i]!=col[j] might be true about 2/3 of the time? Actually probability two random colors from 3 are different is (1 - 1/3) = 2/3. So we still compute k for about 5.3M pairs. That's fine.
Alternatively, we can also precompute something to speed up? Probably not needed.
But note: The bad triple condition includes j-i = k-j, so we can also loop over j as middle? Another approach: For each j, consider i and k symmetric around j: i = j - d, k = j + d for d >=1. Then we can loop j from 0 to N-1 and d from 1 to min(j, N-1-j). That yields same number of iterations: sum_{j} min(j, N-1-j) which is roughly N^2/4 = 4e6 for N=4000? Actually approximate: For j near middle, min(j, N-1-j) is about N/2; total pairs is roughly sum_{d=1}^{N/2} 2*(N/2 - d)??? Let's compute: The number of symmetric pairs (i,k) around j is exactly number of d such that i>=0 and k<N. That is min(j, N-1-j). So total pairs = sum_{j=0}^{N-1} min(j, N-1-j). This sum equals floor(N^2/4). For N even, N=4000, sum = (N^2)/4 = 4,000,000? Actually N^2/4 = 16,000,000/4 = 4,000,000? Wait N^2 = 16,000,000; divide by 4 = 4,000,000. But earlier we said N(N-1)/2 ≈ 8,000,000. So symmetric enumeration yields about half the pairs. Because each (i,j,k) with j middle yields exactly one pair (i,k) for each j, but the (i,j) enumeration yields each triple once as (i,j) with j middle? Actually each triple (i,j,k) with arithmetic progression has a unique middle j. So enumerating by j and d yields exactly one iteration per triple. The number of such (j,d) pairs is exactly number of arithmetic progression triples (i,j,k) with equal step, regardless of colors. That number is sum_{j} min(j, N-1-j). This is about N^2/4 ≈ 4e6 for N=4000, which is less than 8e6. However, our earlier (i,j) enumeration includes all pairs (i,j) but we only proceed to k if k is integer and < N. For those (i,j) that produce a valid k, the count is exactly the same as number of arithmetic progression triples. But in the (i,j) enumeration, we iterate over all 8e6 pairs and then check k < N condition, which is extra overhead. However the (j,d) enumeration loops over only the 4e6 valid middle indices, thus might be more efficient. But we also need to check distinctness. So we could implement bad enumeration as:
bad = 0
for j in range(N):
left = j - 1
right = j + 1
max_d = min(j, N-1-j) # d max such that j-d >=0 and j+d < N
for d in range(1, max_d+1):
i = j - d
k = j + d
if colors are all distinct: bad += 1
That loops over about 4 million iterations. That's about half of 8 million. Could be faster. However, note that the (i,j) enumeration we already have to do for total_distinct? No, we replaced total_distinct with O(N) method. So we only have the bad loop. If we use the symmetric loop, we might reduce from 8 million to 4 million, which is a decent saving. For N=4000, 4 million vs 8 million, both fine, but 4 million might be quicker.
But careful: The symmetric enumeration counts triples where j is the middle index. That indeed covers all arithmetic progression triples exactly once. So it's correct.
Thus I'll adopt the symmetric enumeration.
Now need to ensure we only count those with distinct colors. So for each (i,j,k) we check if col[i], col[j], col[k] are all different. That is a simple condition.
Implementation: for j in range(N): for d in range(1, min(j, N-1-j)+1): i=j-d; k=j+d; if col[i]!=col[j] and col[j]!=col[k] and col[i]!=col[k]: bad+=1.
Now note that the j loop runs N times, inner loop varies. The total number of iterations is sum_{j} min(j, N-1-j). For N=4000, that sum = floor(N^2/4). For even N = 4000, exactly N^2/4 = 16,000,000/4 = 4,000,000. For odd N, slightly less. So 4 million loops, each a few operations. That's fine.
Thus overall algorithm:
- Read N, S.
- Convert to list of ints (0,1,2).
- Precompute prefix counts: pre[i][c] for i from 0 to N (size N+1).
- Precompute suffix counts: suff[i][c] for i from 0 to N (size N+1).
- Compute total_distinct via O(N) loop.
- Compute bad via symmetric loops O(N^2/4).
- answer = total_distinct - bad.
- print answer.
Double-check with example: N=4, indices 0,1,2,3.
Symmetric loops:
j=0: max_d = min(0,3) = 0 => none.
j=1: max_d = min(1,2)=1 => d=1: i=0,k=2; colors: R,R,G -> not all distinct.
j=2: max_d = min(2,1)=1 => d=1: i=1,k=3; colors: R,G,B -> all distinct, bad=1.
j=3: max_d = min(3,0)=0 => none.
bad=1. total_distinct=2 => answer=1. OK.
Now test another case: N=3, all distinct colors RGB. total_distinct? All triples (0,1,2) are all distinct, so total_distinct=1. For bad: check j=1 only: d=1: i=0,k=2; colors R,G,B distinct. j-i=1, k-j=1 equal. So bad=1. Answer = 1-1=0. So no triple satisfies both conditions (since j-i==k-j). That matches condition: j-i != k-j. So none.
If N=3 with RRR: total_distinct=0, bad=0 (since not all distinct), answer=0.
Now test N=6, all distinct colors in some pattern? We'll manually compute maybe. But fine.
Thus algorithm appears correct.
But let's ensure we didn't misinterpret condition: The triple must satisfy both conditions: S_i != S_j, S_i != S_k, S_j != S_k, and j - i != k - j. So indeed we want distinct colors and not arithmetic progression.
Our subtraction method: total distinct - distinct & arithmetic progression = distinct & not arithmetic progression. So correct.
Now implement.
Edge Cases: Large N, answer may be large but Python int fine.
Now we need to consider performance. The symmetric loop: for j in range(N): max_d = min(j, N-1-j). We'll compute limit = min(j, N-1-j). For each d from 1 to limit, we compute i=j-d, k=j+d. Then we check distinctness.
One optimization: We can pre-check if colors[i]==colors[j]? But we need all three distinct, so condition is col[i]!=col[j] and col[j]!=col[k] and col[i]!=col[k]. We can compute if col[i]==col[j] then skip; but then we still need to check col[j]!=col[k] and col[i]!=col[k]? Actually if col[i]==col[j], then it fails distinctness, so we can skip. Similarly if col[j]==col[k], skip. But we must also ensure col[i]!=col[k]? If col[i]!=col[j] and col[j]!=col[k], but col[i] could equal col[k] still fails. So we need to check all. However for early exit, we can test col[i]!=col[j] and col[j]!=col[k] and col[i]!=col[k]. But we could also test if len(set) == 3. In Python, using set on three small ints might be okay but overhead. Better to use simple if with and.
Since the loop is only 4M, overhead of three comparisons is fine.
We can also attempt to precompute something like for each pair (i,k) symmetric around j? Not needed.
Thus implement.
Now we must also confirm that the total_distinct computed via O(N) method counts each triple exactly once, including those with arithmetic progression. Yes.
Now final answer.
Let's test with second example to ensure correctness, but we trust.
One more verification: If N=4000, pre and suff arrays are size N+1 each with 3 ints, so memory okay.
Potential pitfalls: In Python, copying lists for pre and suff each step of the loop might be expensive if we do pre[i+1] = pre[i].copy() and similarly suff[i] = suff[i+1].copy(). That would be O(N) copies of 3-element lists, which is O(N) overall and fine. But we can avoid copying by using two-dimensional list and updating in place using previous counts plus increment. However, to have independent lists for each index, we need to copy or we can use list of lists where each entry is a new list derived from previous. For speed, we can pre-allocate a list of N+1 lists each of length 3, and then fill using loops:
pre = [[0]*3 for _ in range(N+1)]
for i in range(N):
for c in range(3):
pre[i+1][c] = pre[i][c]
pre[i+1][col[i]] += 1
That's O(N*3) operations, no copying of lists (just assignments). Similarly for suff.
But we can also use array of shape (N+1,3) using list comprehension. That's fine.
Let's design:
col = [0 if ch=='R' else 1 if ch=='G' else 2 for ch in S]
pre = [[0]*3 for _ in range(N+1)]
for i in range(N):
pre[i+1][0] = pre[i][0]
pre[i+1][1] = pre[i][1]
pre[i+1][2] = pre[i][2]
pre[i+1][col[i]] += 1
Alternatively, we can use:
pre[i+1] = pre[i].copy()
But copying a 3-element list is cheap, but we can do the manual assignment for clarity.
Similarly, suff = [[0]*3 for _ in range(N+1)]
for i in range(N-1, -1, -1):
suff[i][0] = suff[i+1][0]
suff[i][1] = suff[i+1][1]
suff[i][2] = suff[i+1][2]
suff[i][col[i]] += 1
Note: We must ensure suff[N] remains [0,0,0] after initialization.
Now compute total_distinct:
total = 0
for j in range(N):
c = col[j]
if c == 0:
total += pre[j][1] * suff[j+1][2] + pre[j][2] * suff[j+1][1]
elif c == 1:
total += pre[j][0] * suff[j+1][2] + pre[j][2] * suff[j+1][0]
else: # c==2
total += pre[j][0] * suff[j+1][1] + pre[j][1] * suff[j+1][0]
Now compute bad:
bad = 0
for j in range(N):
max_d = min(j, N-1-j) # because i=j-d >=0, k=j+d <= N-1
for d in range(1, max_d+1):
i = j - d
k = j + d
if col[i] != col[j] and col[j] != col[k] and col[i] != col[k]:
bad += 1
Now answer = total - bad; print.
Double-check: For j=1 in N=4, max_d=min(1,2)=1, i=0,k=2: colors (0,0,1) fails distinctness, so not added. For j=2, max_d=1, i=1,k=3: colors (0,1,2) passes.
Ok.
Now confirm with some random small N by brute force to ensure no off-by-one.
We'll mentally test with N=5, S= "RGRBG". Indices:0:R,1:G,2:R,3:B,4:G? Actually string: R G R B G (if "RGRBG": 0:R,1:G,2:R,3:B,4:G). Let's compute manually all triples with distinct colors: List all combos i<j<k. We'll compute total_distinct and bad then answer.
I'll do brute mental: N=5, indices 0..4.
Triples:
(0,1,2): R,G,R -> not distinct (R appears twice)
(0,1,3): R,G,B -> distinct, distances:1-0=1,3-1=2 -> 1!=2, so valid.
(0,1,4): R,G,G -> G repeats, no.
(0,2,3): R,R,B -> no.
(0,2,4): R,R,G? Actually 0:R,2:R,4:G -> R repeats, no.
(0,3,4): R,B,G -> distinct? R,B,G all different, distances:3-0=3,4-3=1 -> 3!=1, valid.
(1,2,3): G,R,B -> distinct? G,R,B all different, distances:2-1=1,3-2=1 -> 1==1, not valid due to equal distances.
(1,2,4): G,R,G -> G repeats, no.
(1,3,4): G,B,G -> G repeats, no.
(2,3,4): R,B,G -> distinct? R,B,G all different, distances:3-2=1,4-3=1 -> 1==1, not valid.
So total distinct = triples (0,1,3), (0,3,4), (1,2,3), (2,3,4) are distinct? Wait (1,2,3) distinct? Yes G,R,B all different, so distinct, (2,3,4) R,B,G distinct. So total distinct = 4. Among these, those with equal distances: (1,2,3) and (2,3,4) both have equal step. So bad = 2. So answer = 2.
Now compute with our algorithm.
col = [0,1,0,2,1] (R=0,G=1,B=2).
Compute pre:
pre[0]=[0,0,0]
i=0 col0=0: pre[1]=[1,0,0]
i=1 col1=1: pre[2]=[1,1,0]
i=2 col2=0: pre[3]=[2,1,0]
i=3 col3=2: pre[4]=[2,1,1]
i=4 col4=1: pre[5]=[2,2,1]
suff:
suff[5]=[0,0,0]
i=4 col4=1: suff[4]=[0,1,0]? Actually starting from 5: copy then inc: suff[4][0]=suff[5][0]=0, suff[4][1]=0? Wait careful: We'll compute explicitly:
Initialize suff = [[0]*3 for _ in range(N+1)]; set suff[N]=[0,0,0].
Then for i from N-1 down to 0:
for c in 0..2: suff[i][c] = suff[i+1][c]
suff[i][col[i]] += 1
So:
i=4 (col=1): suff[4] = [0,0,0] initially? Actually we assign: suff[4][c] = suff[5][c] for each c, which is 0. Then inc col 1: suff[4][1]=1. So suff[4]=[0,1,0].
i=3 (col=2): suff[3] = suff[4] -> [0,1,0]; then inc col2: suff[3][2]=1 => [0,1,1].
i=2 (col=0): suff[2] = suff[3] -> [0,1,1]; inc col0: [1,1,1].
i=1 (col=1): suff[1] = suff[2] -> [1,1,1]; inc col1: [1,2,1].
i=0 (col=0): suff[0] = suff[1] -> [1,2,1]; inc col0: [2,2,1].
Now total_distinct via j:
j=0, col=0: pre[0]=[0,0,0]; suff[1]=[1,2,1]? Wait suff[1] = [1,2,1]. pre[0][1]suff[1][2] = 01=0; pre[0][2]suff[1][1]=02=0; total=0.
j=1, col=1: pre[1]=[1,0,0]; suff[2]=[1,1,1]? Actually suff[2] = [1,1,1]. Since c=1, use pre[1][0]suff[2][2] + pre[1][2]suff[2][0] = 11 + 01 = 1. That corresponds to triple with j=1, i from pre with color0 before j (i=0), k from suff with color2 after j (k=3?) Actually pre[1][0]=1 means there is one R before index1 (i=0). suff[2][2]=1 means there is one B after index1? But after j, we use suff[j+1]=suff[2], which counts from index2 onward. B appears at index3. So triple (0,1,3) is counted. Good.
j=2, col=0: pre[2]=[1,1,0]; suff[3]=[0,1,1]. c=0 => use pre[2][1]suff[3][2] + pre[2][2]suff[3][1] = 11 + 01 = 1. That would count triple with j=2, i before with color1 (i=1) and k after with color2 (k=3) => (1,2,3). That's a distinct triple but we also have (0,2,?) but not. Actually we need to also count (0,2,3)? That would be i=0 (R), j=2 (R) not distinct because same color. So only (1,2,3) is counted. But also could there be i before with color2? None. So that's one.
j=3, col=2: pre[3]=[2,1,0]; suff[4]=[0,1,0]. c=2 => use pre[3][0]suff[4][1] + pre[3][1]suff[4][0] = 21 + 10 = 2. That counts: i before with color0 (R) and k after with color1 (G): indices? pre[3][0]=2 (i=0,2) ; suff[4][1]=1 (k=4) => yields two triples: (0,3,4) and (2,3,4). Both distinct. Good.
j=4, col=1: pre[4]=[2,1,1]; suff[5]=[0,0,0]; c=1 => pre[4][0]suff[5][2] + pre[4][2]suff[5][0] = 20 + 10 = 0.
Sum total = 0+1+1+2+0=4. matches.
Now bad via symmetric loops:
j=0: max_d=0
j=1: max_d = min(1,3)=1 -> d=1: i=0,k=2: colors 0,1,0 -> not distinct, no.
j=2: max_d = min(2,2)=2 -> d=1: i=1,k=3: colors 1,0,2 -> distinct? (G,R,B) yes, bad+=1; d=2: i=0,k=4: colors 0,0,1? Actually col[0]=0, col[2]=0, col[4]=1 -> not distinct (0,0,1). So only d=1.
j=3: max_d = min(3,1)=1 -> d=1: i=2,k=4: colors 0,2,1 -> distinct? (R,B,G) yes, bad+=1.
j=4: max_d=0
bad=2. total-bad=2. matches our manual answer.
Thus algorithm correct.
Now we should think about potential integer overflow? In Python, not an issue.
Now check constraints: N up to 4000. Our loops: O(N) for pre/suff and total, O(N^2/4) for bad. For N=4000, bad iterations = 4e6, which is very fine.
Thus solution is efficient.
But we need to be careful about indexing when computing pre and suff: For pre[i] we store counts for indices < i. For suff[i] we store counts for indices >= i. So for j, we need pre[j] and suff[j+1]. That's correct.
Now we can implement.
But wait, there might be an alternative: Could we directly compute answer by counting triples that satisfy both conditions without subtraction? Possibly, but subtraction is easier and safe.
Now consider edge case where N=4000 and string consists of all same color? Then total_distinct=0, bad=0, answer=0. Works.
Now time to write code.
But let's consider if we can further micro-opt: For computing total_distinct, we can compute on the fly without storing full pre and suff by using cumulative counts? But we need both sides for each j, so storing both is fine.
We can also reduce memory by using two arrays: prefix as list of tuples, but it's fine.
Now potential pitfalls: When computing pre[i+1] = pre[i] then increment, we must ensure we don't modify previous list. If we assign pre[i+1] = pre[i] then we have same reference, so we need to copy. So either copy list or assign each element manually.
I'll implement manual assignment for clarity and speed (avoid copying list objects).
Pseudo-code:
N = int(input())
S = input().strip()
color = [0 if c=='R' else 1 if c=='G' else 2 for c in S]
pre: (N+1) x 3
pre = [[0,0,0] for _ in range(N+1)]
for i in range(N):
pre[i+1][0] = pre[i][0]
pre[i+1][1] = pre[i][1]
pre[i+1][2] = pre[i][2]
pre[i+1][color[i]] += 1
suff: (N+1) x 3
suff = [[0,0,0] for _ in range(N+1)]
for i in range(N-1, -1, -1):
suff[i][0] = suff[i+1][0]
suff[i][1] = suff[i+1][1]
suff[i][2] = suff[i+1][2]
suff[i][color[i]] += 1
total = 0
for j in range(N):
c = color[j]
if c == 0: # R
total += pre[j][1] * suff[j+1][2] + pre[j][2] * suff[j+1][1]
elif c == 1: # G
total += pre[j][0] * suff[j+1][2] + pre[j][2] * suff[j+1][0]
else: # B
total += pre[j][0] * suff[j+1][1] + pre[j][1] * suff[j+1][0]
bad = 0
for j in range(N):
# left = j, right = N-1-j
max_d = j if j < N-1-j else N-1-j
# Actually min(j, N-1-j)
limit = min(j, N-1-j)
for d in range(1, limit+1):
i = j - d
k = j + d
ci, cj, ck = color[i], color[j], color[k]
if ci != cj and cj != ck and ci != ck:
bad += 1
print(total - bad)
We can also compute limit = min(j, N-1-j) directly.
Now test again with given examples.
We'll simulate first example: N=4, S=RRGB => colors: 0,0,1,2. pre and suff as before. total = computed 2, bad = 1 => output 1.
Second example: We'll trust.
Now check N=3 RGB: total = 1, bad = 1 => output 0.
N=3 RRR: total=0, bad=0 ->0.
Now potential issue: For total computation, we used pre[j] and suff[j+1]. That works because pre[j] counts indices < j, suff[j+1] counts indices > j.
Now, let's think about the case where j is at boundaries: j=0 -> pre[0] = [0,0,0]; suff[1] counts from index1 to end. The formula for c==0 would add pre[0][1]*suff[1][2] etc, which is 0, correct. Similarly j=N-1: suff[N] = [0,0,0]; pre[N-1] counts before, so formula yields 0.
Now performance: For bad loop, limit = min(j, N-1-j). For each j, we iterate over d. The sum of limits = floor(N^2/4). For N=4000, that's 4,000,000 exactly (since 4000 even). That's fine. However, note that in Python, loops with range(1, limit+1) and simple operations will be okay. Usually 4 million iterations is quick (<0.1 seconds). But we also have to consider overhead of the outer j loop (4000 times). So total maybe 4 million + overhead. That's fine.
But wait: The sum of limits for N=4000 is actually N^2/4 = 4,000,000? Let's compute: For even N, sum_{j=0}^{N-1} min(j, N-1-j) = N^2/4. N=4000 => 16,000,000/4 = 4,000,000. Yes.
Now also note: In worst-case string, we might do the if condition for all triples, that's fine.
Now I think it's correct.
But is there any subtlety: The condition j-i != k-j. In our subtraction we considered only those with equal step. But what about triples where j-i = k-j but we subtract them from total distinct. That's fine.
Now confirm that total_distinct includes all triples where colors are all distinct, regardless of distances. Yes.
Thus answer is correct.
We should also consider alternative edge: The problem statement says "j - i \neq k - j". So they consider the distances. Our symmetric enumeration counts exactly those with j-i = k-j. So we subtract them.
Now let's verify with another random test: N=6, S=RRRGGGBBBB? But we can compute by brute in head maybe not.
We'll test with N=5 we already did.
Now I will consider an alternative approach for fun: But no.
Now before finalizing, double-check that we haven't misinterpreted condition "j - i \neq k - j". It says not equal, so we want them to be different. So we keep those that are different. So total distinct minus those with equal step.
All good.
Now I'll also double-check that there is no double counting in total distinct via O(N) method: It counts each triple exactly once as middle j. Because in any triple i<j<k, the middle index is uniquely j. So it's correct.
Now potential issue: The triple might have i and k both same side? No.
Now we need to make sure we don't subtract something that is not counted: For a triple with distinct colors and equal step, we subtracted exactly once. Since we computed total distinct using j as middle, and then subtracted those with equal step, but note that for equal step triples, j is indeed the middle index, and they are counted in total distinct. So subtraction is correct.
Now we must ensure that we do not double count the bad triples in our subtraction: In our bad enumeration, each bad triple is counted exactly once because for each such triple, there is a unique middle j, and we iterate over j and d, and we add to bad only if distinct colors. So each bad triple contributes 1 to bad. So subtraction correct.
Now we must ensure that total and bad are computed correctly for large N and that answer may be negative? No.
Now proceed to code.
But before coding, let's also think about potential pitfalls: Our mapping: 'R'->0, 'G'->1, 'B'->2. If the string contains only uppercase letters as per problem. So mapping is fine.
Now, we could also compute total distinct by counting all triples minus those with some same color, but we have O(N) method.
Now let's evaluate the code's performance with Python (PyPy). I'll write the code accordingly.
Now consider memory: pre and suff arrays of size 4001 x 3 each, that's 400132 ~ 24006 integers, trivial.
Now one more possible optimization: Instead of storing entire suffix array, we could compute suffix counts on the fly while iterating j for total distinct? But it's fine.
Now I will write the code.
But I must be careful that I didn't misinterpret the indexing: In the problem, indices are 1-indexed, but our code uses 0-indexed, which is fine because we only care about differences: j-i (0-indexed differences) are same as 1-indexed differences because subtraction shifts cancel: (j+1)-(i+1) = j-i. So condition j-i != k-j is equivalent when using 0-indexed indices. So no issue.
Now confirm: For i=0,j=1,k=2 (0-index), j-i=1, k-j=1, so it's an arithmetic progression. In 1-indexed, i=1,j=2,k=3: differences also 1. So condition holds.
Thus correct.
Now we should test with sample 2 to ensure output 1800. But we'll trust.
Now write final answer.
But maybe there is a corner: The total_distinct formula might double count or miss some triples if we incorrectly used pre[j] (counts before j) and suff[j+1] (counts after j). Check: For j=0, pre[0] is before, correct. For j=N-1, suff[N] is after, correct.
Now also need to ensure that in the total_distinct formula, when we multiply pre[j][a] * suff[j+1][b], that counts triples where i has color a and k has color b, with i<j<k. That's correct. And the other term counts i with b and k with a. So all.
Now for computing total, we can also write generic code using loops over other colors to avoid if-else, but if-else is fine.
Now code.
But wait: Could we combine the calculation of total and bad in one pass? Not needed.
Now final step: Print answer as integer.
Now I'll produce final solution.
One more check: N=4000, both loops may be a bit heavy but should be fine. However, we must avoid using Python's default loops with large overhead for inner loops? But 4 million loops is fine. Let's estimate: In PyPy, 10 million simple loops can be done in <0.5 seconds. In CPython, maybe ~0.3-0.5 seconds for 4 million? Actually CPython may do about 30-50 million simple operations per second? I'm not sure. But typical AtCoder problems with N=2000 and O(N^2) double nested loops (2 million) run in Python about 0.2 seconds, so 8 million maybe 0.8 seconds, 4 million maybe 0.4 seconds. With both loops plus pre/suff, still under 2 seconds. Many Python solutions for this problem (AtCoder ABC162 D - I think it's that problem) use O(N^2) and pass. Actually this is exactly ABC162 D - "RGB Triplets". Yes, I recall problem. Indeed the constraints N<=4000 and there is an O(N^2) solution. So it's fine.
But note: In ABC162 D, there is a known trick: Count all triples with distinct colors, then subtract those where (j-i) = (k-j) and colors are distinct. So exactly our approach. Many solutions use O(N^2) loops for both. So fine.
But one nuance: In ABC162 D, the problem originally had N <= 4000 and S consists of 'R','G','B'. The solution often uses O(N^2) enumeration of i and j, and count k with suffix array. That's exactly what we have.
But there is also a known pitfall: When counting total distinct, some may compute as total = total triples - #triples with at least two same, using combinatorics: C(N,3) - sum_{c} C(cnt[c],2)(N-cnt[c]) - sum_{c} C(cnt[c],3)? Actually formula: triples with at least two same = sum_{c} (choose two of c and any other (including same?))? Let's not worry.
But our O(N) method using middle j is even better.
Now implement.
Now let's produce final answer.
But we should also test with a random small N by brute force to ensure our code works. I can't run code here, but we can mentally simulate.
Now I will write final solution in Python.
One small improvement: For bad enumeration, we can pre-compute for each j the limit and loop. But that's fine.
Now here's the code:
def solve():
import sys
input = sys.stdin.readline
N = int(input().strip())
S = input().strip()
col = [0 if c == 'R' else 1 if c == 'G' else 2 for c in S]
# prefix counts
pre = [[0]*3 for _ in range(N+1)]
for i in range(N):
pre[i+1][0] = pre[i][0]
pre[i+1][1] = pre[i][1]
pre[i+1][2] = pre[i][2]
pre[i+1][col[i]] += 1
# suffix counts
suff = [[0]*3 for _ in range(N+1)]
for i in range(N-1, -1, -1):
suff[i][0] = suff[i+1][0]
suff[i][1] = suff[i+1][1]
suff[i][2] = suff[i+1][2]
suff[i][col[i]] += 1
total = 0
for j in range(N):
c = col[j]
if c == 0:
total += pre[j][1] * suff[j+1][2] + pre[j][2] * suff[j+1][1]
elif c == 1:
total += pre[j][0] * suff[j+1][2] + pre[j][2] * suff[j+1][0]
else:
total += pre[j][0] * suff[j+1][1] + pre[j][1] * suff[j+1][0]
bad = 0
for j in range(N):
limit = min(j, N-1-j)
for d in range(1, limit+1):
i = j - d
k = j + d
ci, cj, ck = col[i], col[j], col[k]
if ci != cj and cj != ck and ci != ck:
bad += 1
print(total - bad)
if name == "main":
solve()
That's the solution.
But note: In the total computation, we used pre[j] and suff[j+1]. For j = N-1, suff[N] is zero, so works.
Now we can also consider using integer indexing from 1 to N in loops but fine.
Now we finalize.
But is there any other nuance? The problem statement: "Find the number of triples (i,~j,k)(1 \leq i < j < k \leq N) that satisfy both of the following conditions: ..." So we output count.
Now I'm confident.
One more check: For N=4000, the total distinct count might be up to C(4000,3) ≈ 10.66e9, which fits in Python int.
Now finalize.
Given that the problem is from AtCoder ABC162 D, the solution is correct.
Thus we can provide answer.
Now in the response we need to produce the final answer: the code.
But the user asked: "We have a string S... Find the number..." They likely want the solution. So we should output the code in Python.
But note: The conversation says "You are ChatGPT...". We should respond with a solution explanation and code. Since the instruction: "We have a string S... Input... Output... Examples..." It seems they want the answer. Usually we provide solution and code. So I'll provide an explanation of the approach and then the final code.
Thus final response: explanation + Python code.
I'll produce a concise explanation: Count total triples with distinct colors, subtract those that also form an arithmetic progression. For total distinct, iterate over middle index and use prefix/suffix counts. For arithmetic progression triples, iterate over middle index and step.
Now output code.
Make sure to include fast I/O.
Now we can also provide alternative method but not needed.
Thus final answer. We can solve the problem by first counting all triples (i, j, k) with i < j < k and all three colors distinct, then subtracting those that also satisfy j - i = k - j (i.e., they form an arithmetic progression).
-
Total distinct triples can be obtained in O(N) by fixing the middle index j and using prefix/suffix counts of the three colors.
For a fixed j with color c, the other two colors are a and b. The number of valid i (< j) with color a and k (> j) with color b is pre[j][a] * suff[j+1][b]; similarly with i color b and k color a. Summing over all j gives the total.
-
Bad triples (distinct colors and j-i = k-j) are exactly the arithmetic progressions. For each middle index j and distance d such that i = j-d and k = j+d are inside the string, check whether the three colors are all different. Count these.
The answer is total_distinct - bad. Both steps are efficient for N ≤ 4000.
import sys
def solve() -> None:
input = sys.stdin.readline
N = int(input())
S = input().strip()
# Map colors to 0,1,2
col = [0 if c == 'R' else 1 if c == 'G' else 2 for c in S]
# Prefix counts: pre[i] = counts of (0..i-1)
pre = [[0, 0, 0] for _ in range(N + 1)]
for i in range(N):
pre[i+1][0] = pre[i][0]
pre[i+1][1] = pre[i][1]
pre[i+1][2] = pre[i][2]
pre[i+1][col[i]] += 1
# Suffix counts: suff[i] = counts of (i..N-1)
suff = [[0, 0, 0] for _ in range(N + 1)]
for i in range(N - 1, -1, -1):
suff[i][0] = suff[i+1][0]
suff[i][1] = suff[i+1][1]
suff[i][2] = suff[i+1][2]
suff[i][col[i]] += 1
# Total triples with all distinct colors
total = 0
for j in range(N):
c = col[j]
if c == 0: # R
total += pre[j][1] * suff[j+1][2] + pre[j][2] * suff[j+1][1]
elif c == 1: # G
total += pre[j][0] * suff[j+1][2] + pre[j][2] * suff[j+1][0]
else: # B
total += pre[j][0] * suff[j+1][1] + pre[j][1] * suff[j+1][0]
# Triples with distinct colors and j-i = k-j (arithmetic progression)
bad = 0
for j in range(N):
limit = min(j, N - 1 - j) # maximum distance d
for d in range(1, limit + 1):
i = j - d
k = j + d
ci, cj, ck = col[i], col[j], col[k]
if ci != cj and cj != ck and ci != ck:
bad += 1
print(total - bad)
if __name__ == "__main__":
solve()