Submission #1326161

#TimeUsernameProblemLanguageResultExecution timeMemory
1326161AgageldiGrowing Vegetable is Fun 3 (JOI19_ho_t3)C++20
100 / 100
359 ms757544 KiB
#include <bits/stdc++.h>
using namespace std;

#define N 401

const int inf = 1e9;

int n, a[3], ans = inf, m, dp[401][401][401][3], pr[N][4];
vector <int> P[3];
string s;

int main() {
    ios::sync_with_stdio(0);cin.tie(0);
    cin >> n >> s;
    bool ok = 0;
    for(int i = 0; i < n; i++) {
        int c = 0;
        if(s[i] == 'R') c = 1;
        if(s[i] == 'Y') c = 2;
        a[c]++;
        P[c].push_back(i);
        if(a[c] > (n + 1) / 2) ok = 1;
        for(int j = 0; j < 3; j++) {
            if(i)pr[i][j] += pr[i - 1][j];
            if(c == j) pr[i][j]++;
        }
    }
    if(ok) return cout << "-1\n", 0;
    for(int i = 0; i <= n; i++) {
        for(int j = 0; j <= n; j++) {
            for(int k = 0; k <= n; k++) {
                for(int z = 0; z <= 2; z++) {
                    dp[i][j][k][z] = inf;
                }
            }
        }
    }
    dp[0][0][0][1] = dp[0][0][0][0] = dp[0][0][0][2] = 0;
    for(int i = 0; i <= a[0]; i++) {
        for(int j = 0; j <= a[1]; j++) {
            for(int k = 0; k <= a[2]; k++) {
                for(int z = 0; z <= 2; z++) {
                    if(dp[i][j][k][z] == inf) continue;
                    for(int p = 0; p <= 2; p++) {
                        if(p == z) continue;
                        int nwi = i + (p == 0);
                        int nwj = j + (p == 1);
                        int nwk = k + (p == 2);
                        if(nwi > a[0]) continue;
                        if(nwj > a[1]) continue;
                        if(nwk > a[2]) continue;
                        int pos = -1, x1 = 0, x2 = 0;
                        if(p == 0) {
                            pos = P[p][i];
                            x1 = max(0, pr[pos][1] - j);
                            x2 = max(0, pr[pos][2] - k);
                        }
                        if(p == 1) {
                            pos = P[p][j];
                            x1 = max(0, pr[pos][0] - i);
                            x2 = max(0, pr[pos][2] - k);
                        }
                        if(p == 2) {
                            pos = P[p][k];
                            x1 = max(0, pr[pos][0] - i);
                            x2 = max(0, pr[pos][1] - j);
                        }
                        dp[nwi][nwj][nwk][p] = min(dp[nwi][nwj][nwk][p],dp[i][j][k][z] + x1 + x2);
                    }
                }
            }
        }
    }
    for(int i = 0; i <= 2; i++) {
        ans = min(ans,dp[a[0]][a[1]][a[2]][i]);
    }
    cout << ans << endl;
    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...