Submission #366082

#TimeUsernameProblemLanguageResultExecution timeMemory
366082Lam_lai_cuoc_doiGrowing Vegetable is Fun 3 (JOI19_ho_t3)C++17
15 / 100
68 ms4332 KiB
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using ull = unsigned long long;

const bool typetest = 0;
const int N = 4e2 + 5;
const int Inf = 1e9 + 7;
int n;
string s;
int dp[2][N][N][3];
int r[N], g[N], y[N];
int a, b, c;

void Read()
{
    cin >> n >> s;
    s = " " + s;
    for (int i = 1; i <= n; ++i)
    {
        if (s[i] == 'R')
            r[++a] = i;
        else if (s[i] == 'G')
            g[++b] = i;
        else
            y[++c] = i;
    }
}

inline void Min(int &x, int y)
{
    if (x > y)
        x = y;
}

void Solve()
{
    fill_n(&dp[0][0][0][0], 2 * N * N * 3, Inf);
    dp[0][0][0][0] = dp[0][0][0][1] = dp[0][0][0][2] = 0;
    for (int i = 0; i <= a; ++i)
    {
        fill_n(&dp[!(i & 1)][0][0][0], N * N * 3, Inf);
        for (int j = 0; j <= b; ++j)
            for (int t = 0; t <= c; ++t)
            {
                if (dp[i & 1][j][t][0] != Inf)
                {
                    if (j < b)
                        Min(dp[i & 1][j + 1][t][1], dp[i & 1][j][t][0] + abs(i + j + 1 + t - g[j + 1]));
                    if (t < c)
                        Min(dp[i & 1][j][t + 1][2], dp[i & 1][j][t][0] + abs(i + j + t + 1 - y[t + 1]));
                }
                if (dp[i & 1][j][t][1] != Inf)
                {
                    if (i < a)
                        Min(dp[!(i & 1)][j][t][0], dp[i & 1][j][t][1] + abs(i + 1 + j + t - r[i + 1]));
                    if (t < c)
                        Min(dp[i & 1][j][t + 1][2], dp[i & 1][j][t][1] + abs(i + j + t + 1 - y[t + 1]));
                }
                if (dp[i & 1][j][t][2] != Inf)
                {
                    if (j < b)
                        Min(dp[i & 1][j + 1][t][1], dp[i & 1][j][t][2] + abs(i + j + 1 + t - g[j + 1]));
                    if (i < a)
                        Min(dp[!(i & 1)][j][t + 1][0], dp[i & 1][j][t][2] + abs(i + 1 + j + t - r[i + 1]));
                }
            }
    }
    int ans = min(dp[a & 1][b][c][0], min(dp[a & 1][b][c][1], dp[a & 1][b][c][2]));
    cout << (ans == Inf ? -1 : ans / 2);
}

int32_t main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t(1);
    if (typetest)
        cin >> t;
    for (int _ = 1; _ <= t; ++_)
    {
        Read();
        Solve();
    }
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...