Score : 400400 points
Problem Statement
We have a string SS.
Constraints
- 1≤N≤40001≤N≤4000 consisting of
R
,G
, andB
.
Input
Input is given from Standard Input in the following format:
NN
Output
Print the number of triplets in question.
Sample Input 1 Copy
Copy
4 RRGB
Sample Output 1 Copy
Copy
1
Only the triplet (1, 3, 4)(1, 3, 4) satisfies the first condition but not the second, so it does not count.
Sample Input 2 Copy
Copy
39 RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB
Sample Output 2 Copy
Copy
1800
//题目意思简单说一下 给你字符串SS 求 下标为i<j<k的三个字母不一样并且j-i!=k-j的有多少个
//显然3层for循环会TLE,所以这个可以使用前缀和
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=4010;
int n,pre[maxn][3],suf[maxn][3];
char s[maxn];
int d[maxn];
ll ans;
int main() {
scanf("%d",&n);
scanf("%s",s+1);
for (int i=1;i<=n;i++) {
if (s[i]=='R') d[i]=0;
else if (s[i]=='G') d[i]=1;
else d[i]=2;
}
for (int i=1;i<=n;i++) { //前缀和
for (int j=0;j<3;j++) pre[i][j]=pre[i-1][j];
pre[i][d[i]]++;
}
for (int i=n;i>=1;i--) { //后缀和
for (int j=0;j<3;j++) suf[i][j]=suf[i+1][j];
suf[i][d[i]]++;
}
for (int i=1;i<=n;i++) {
for (int j=0;j<3;j++)
for (int k=0;k<3;k++)
if (d[i]!=j&&j!=k&&k!=d[i]) //3个字母不同 i为中间的字母,j为前面的,k为后面的。然后相乘组合就可以了
ans+=pre[i-1][j]*suf[i+1][k];
}
for (int i=1;i<=n;i++)
for (int j=i+1,k;j<=n;j++) { //处理j-i==k-j的情况
k=j*2-i;
if (j<k&&k<=n) {
if (d[i]!=d[j]&&d[j]!=d[k]&&d[k]!=d[i]) ans--;
}
}
printf("%lld\n",ans);
return 0;
}