// IamHereForFun //
#include <bits/stdc++.h>
using namespace std;
#define LSOne(S) ((S) & -(S))
const int N = 4e2 + 5;
const int M = 2e5 + 5;
const int Q = 1e5 + 5;
const int LG = 20;
const long long INF = -1e18;
const int MOD = 1e9 + 7;
const int B = 350;
int n, c1, c2, c3, dp1[3][N], dp2[3][N], mn = 1e9, l1[3][3], l2[3][3];
string s;
void solve()
{
cin >> n >> s;
c1 = count(s.begin(), s.end(), 'R');
c2 = count(s.begin(), s.end(), 'G');
c3 = count(s.begin(), s.end(), 'Y');
if (max(max(c1, c2), c3) > (n + 1) / 2)
{
cout << -1;
return;
}
for (int x = 0; x < 3; x++)
{
for (int y = 0; y <= n + 1; y++)
{
dp2[x][y] = 1e9;
dp1[x][y] = 1e9;
}
for(int y = 0; y < 3; y++)
{
l1[x][y] = 1e9;
l2[x][y] = 1e9;
}
}
// th chi co 2 cay
// |cnt1 - cnt2| <= 1
// => zigzag, sau do tinh dc
// th chinh N <= 60?
// dp[i][cntR][cntG] = so op it nhat de lượng cây ở sau bang cntR?
// dp[3][i][cnt]? số op ít nhất để lượng cây có tính chat như trên =))
// dung dp1, dp2 để op bộ nhớ + dễ code
// th1: s1 = 'R'
// cnt > 1
// dp1[0][cnt] = dp2[0][cnt - 1]
// dp1[1][cnt] = dp2[1][cnt + 1] + cnt
// dp1[2][cnt] = dp2[2][cnt + 1] + cnt
for (int x = 0; x < n; x++)
{
int i = 0;
char c = s[x];
if (c == 'R')
i = 0;
if (c == 'G')
i = 1;
if (c == 'Y')
i = 2;
if (x == 0)
{
for(int y = 0; y < 3; y++) if(y != i) l1[y][i] = 0;
continue;
}
for (int y = 0; y < 3; y++)
{
for (int z = 2; z <= x + 1; z++)
{
if (y == i)
{
dp2[y][z] = min(dp2[y][z], dp1[y][z - 1]);
if (z == 2)
{
for (int t = 0; t < 3; t++)
{
dp2[y][z] = min(dp2[y][z], l1[t][y]);
}
}
}
else
{
dp2[y][z] = min(dp2[y][z], dp1[y][z + 1] + z);
}
}
if (y == i)
{
// y == current color
for (int z = 0; z < 3; z++)
{
if (z != y)
{
for (int t = 0; t < 3; t++)
{
l2[z][y] = min(l2[z][y], l1[t][z]);
}
}
}
}
else
{
// y != current color
l2[i][y] = min(l2[i][y], dp1[y][2] + 1);
for(int z = 0; z < 3; z++)
{
if(z != i)
{
l2[i][y] = min(l2[i][y], l1[z][y] + 1);
}
}
}
}
for (int y = 0; y < 3; y++)
{
for (int z = 1; z <= x + 1; z++)
{
dp1[y][z] = dp2[y][z];
// cout << dp1[y][z] << " " << y << " " << z << " " << x << "\n";
dp2[y][z] = 1e9;
}
for(int z = 0; z < 3; z++)
{
l1[y][z] = l2[y][z];
l2[y][z] = 1e9;
}
}
}
for (int x = 0; x < 3; x++)
{
for(int y = 0; y < 3; y++)
{
mn = min(mn, l1[x][y]);
}
}
cout << mn;
}
signed main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t = 1;
// cin >> t;
for (int x = 1; x <= t; x++)
{
solve();
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |