이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
#define N 402
using namespace std;
int n, v[N], pos[3][N], sz[3], inf = 2000000000, ans = 2000000000;
int dp[N][N][N][3], dij[N][N], diz[N][N], dji[N][N], dzi[N][N], djz[N][N], dzj[N][N];
int solve()
{
for(int i = 0; i <= sz[0]; i++)
{
for(int j = 0; j <= sz[1]; j++)
{
for(int z = 0; z <= sz[2]; z++)
{
for(int lst = 0; lst <= 2; lst ++)
{
if(!i and !j and !z)
{
dp[i][j][z][lst] = 0;
continue;
}
int A = inf, B = inf, C = inf, di = 0, dj = 0, dz = 0;
if(i > 0 and lst != 0) A = dp[i - 1][j][z][0]+ abs(i + j + z - pos[0][i] + di + dij[i][j + 1] + diz[i][z + 1]);
if(j > 0 and lst != 1) B = dp[i][j - 1][z][1] + abs(i + j + z - pos[1][j] + dj + dji[i + 1][j] + djz[z + 1][j]);
if(z > 0 and lst != 2) C = dp[i][j][z - 1][2] + abs(i + j + z - pos[2][z] + dz + dzi[i + 1][z] + dzj[z][j + 1]);
dp[i][j][z][lst] = min({A, B, C});
if(i + j + z == n) ans = min(ans, dp[i][j][z][lst]);
}
}
}
}
return ans;
}
int main()
{
ios::sync_with_stdio(false); cin.tie(0);
cin>>n;
for(int i = 1; i <= n; i++)
{
char c;
cin>>c;
if(c == 'R') v[i] = 0;
else if(c == 'Y') v[i] = 1;
else v[i] = 2;
++sz[v[i]];
pos[v[i]][sz[v[i]]] = i;
}
for(int i = sz[0]; i >= 1; i--)
{
for(int a = sz[1]; a >= 1; a--)
{
if(pos[1][a] < pos[0][i]) dij[i][a] = dij[i][a + 1] + 1;
else dij[i][a] = dij[i][a + 1];
if(pos[0][i] < pos[1][a]) dji[i][a] = dji[i + 1][a] + 1;
else dji[i][a] = dji[i + 1][a];
}
for(int a = sz[2]; a >= 1; a--)
{
if(pos[2][a] < pos[0][i]) diz[i][a] = diz[i][a + 1] + 1;
else diz[i][a] = diz[i][a + 1];
if(pos[0][i] < pos[2][a]) dzi[i][a] = dzi[i + 1][a] + 1;
else dzi[i][a] = dzi[i + 1][a];
}
}
for(int z = sz[2]; z >= 1; z--)
{
for(int j = sz[1]; j >= 1; j--)
{
if(pos[1][j] < pos[2][z]) dzj[z][j] = dzj[z][j + 1] + 1;
else dzj[z][j] = dzj[z][j + 1];
if(pos[2][z] < pos[1][j]) djz[z][j] = djz[z + 1][j] + 1;
else djz[z][j] = djz[z + 1][j];
}
}
int ans = solve();
cout<<(ans >= inf ? -1 : ans)<<"\n";
}
# | 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... |