AtCoder Beginner Contest 162 D.RGB Triplets

AtCoder Beginner Contest 162 D.RGB Triplets

题目链接

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 ≤ i < j < k ≤ N ) (i, j, k) \ (1≤i(i,j,k) (1i<j<kN) that satisfy both of the following conditions:

  • S i ≠ S j , S i ≠ S k , a n d S j ≠ S k . S_i≠S_j, S_i≠S_k, and S_j≠S_k. Si=Sj,Si=Sk,andSj=Sk.
  • j − i ≠ k − j . j−i≠k−j. ji=kj.

Constraints

  • 1 ≤ N ≤ 4000 1≤N≤4000 1N4000
  • 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

Sample Input 2

39
RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB

Sample Output 2

1800

这题首先找所有三元组的个数,然后用循环遍历去掉不符合条件的三元组即可,复杂度 O ( ( n 2 ) 2 ) O((\frac{n}{2})^2) O((2n)2),AC代码如下:

#include
using namespace std;
typedef long long ll;

int main(){
     
    int len;
    string s;
    cin>>len>>s;
    ll s1=0,s2=0,s3=0,sum=0;
    for(int i=0;i<len;i++){
     
        if(s[i]=='R') sum+=s2*s3,s1++;
        if(s[i]=='G') sum+=s1*s3,s2++;
        if(s[i]=='B') sum+=s1*s2,s3++;
    }
    for(int i=0;i<len;i++){
     
        for(int j=i;j<len;j+=2){
     
            if(s[i]!=s[j] && s[i]!=s[(i+j)/2] && s[j]!=s[(i+j)/2]) sum--;
        }
    }
    cout<<sum;
    return 0;
}

你可能感兴趣的:(暴力,字符串,AtCoder)