RGB String#12320

RGB String (Editorial)

Problem Author:

Andriy Kholod (Connect)

Prepared by:

Andriy Kholod (Connect)

Analysis:

Andriy Kholod (Connect)

Solution

Consider a segment of length . Let's place the element in the first position, in the second, and in the third. Then we consider the elements that are already in the triplet that ends at position , where position has and position has . Thus, the only element we can place in position is . We will arrange the elements in positions and using the same principle. The condition of beauty will also be maintained in the triplets that start at positions and .

Then, by the same principle, we can prove that a solution does not exist for all that are not divisible by .

Thus, the solution to the problem will be to try all possible arrangements of the elements , , and without repetitions and choose the most advantageous option.

The asymptotic complexity of the solution is .

#include <bits/stdc++.h>

using namespace std;

#define ll long long
#define speed ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define endl '\n'
#define pb push_back

const ll clasik = 2e5+17;
const ll INF = 1e17;
ll w[clasik] , pref[clasik] , poslid[clasik];

void solve() {

    ll n;

    cin>>n;

    string line;

    cin>>line;

    if (n%3 != 0) {
        cout<<-1<<endl;
        return;
    }

    ll res = INF;

    //R G B


    ll curr = 0;

    for (int i = 0 ; i < n ; i+=3) {
        curr += (line[i]!='R');
        curr += (line[i+1]!='G');
        curr += (line[i+2]!='B');
    }

    res = min(res , curr);

    // R B G

    curr = 0;

    for (int i = 0 ; i < n ; i+=3) {
        curr += (line[i]!='R');
        curr += (line[i+1]!='B');
        curr += (line[i+2]!='G');
    }

    res = min(res , curr);

    // B R G

    curr = 0;

    for (int i = 0 ; i < n ; i+=3) {
        curr += (line[i]!='B');
        curr += (line[i+1]!='R');
        curr += (line[i+2]!='G');
    }

    res = min(res , curr);

    // B G R

    curr = 0;

    for (int i = 0 ; i < n ; i+=3) {
        curr += (line[i]!='B');
        curr += (line[i+1]!='G');
        curr += (line[i+2]!='R');
    }

    res = min(res , curr);

    // G R B

    curr = 0;

    for (int i = 0 ; i < n ; i+=3) {
        curr += (line[i]!='G');
        curr += (line[i+1]!='R');
        curr += (line[i+2]!='B');
    }

    res = min(res , curr);

    // G B R

    curr = 0;

    for (int i = 0 ; i < n ; i+=3) {
        curr += (line[i]!='G');
        curr += (line[i+1]!='B');
        curr += (line[i+2]!='R');
    }

    res = min(res , curr);

    cout<<res<<endl;

}  

signed main() {
    speed;
    int test;
    test = 1;
    //cin>>test;
    while (test--) solve();
    return 0;
}