#include <iostream>
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const ll maxn = 2*1e5+5, INF = 1e8+9;
void solve(){
int n, k;
cin >> n >> k;
string s;
cin >> s;
s = ' ' + s;
vector<int> J(n+2, 0), O(n+2, n+1), I(n+2, n+1);
for(int i = n; i >= 1; i--){
if(s[i] == 'O'){
O[i] = i;
}else{
O[i] = O[i+1];
}
}
for(int i = 1; i <= n; i++){
if(s[i] == 'O'){
O[i] = O[i+1];
}
}
int j = -1, cnt = 0;
for(int i = 1; i <= n; i++){
if(s[i] == 'O'){
cnt++;
if(cnt == k){
j = i;
break;
}
}
}
if(j == -1){
cout << -1;
return;
}
vector<int> pfO(n+2, INF), OO(n+2, n+1);
for(int i = 1; i <= n; i++){
if(s[i] == 'O'){
pfO[i] = j-i+1 - k;
OO[i] = j;
j = O[j];
}
if(j == n+1) break;
}
for(int i = n; i >= 1; i--){
if(s[i] == 'I'){
I[i] = i;
}else{
I[i] = I[i+1];
}
}
for(int i = 1; i <= n; i++){
if(s[i] == 'I'){
I[i] = I[i+1];
}
}
cnt = 0;
j = -1;
for(int i = 1; i <= n; i++){
if(s[i] == 'I'){
cnt++;
if(cnt == k){
j = i;
break;
}
}
}
if(j == -1){
cout << -1;
return;
}
vector<int> pfI(n+2, INF);
for(int i = 1; i <= n; i++){
if(s[i] == 'I'){
pfI[i] = j-i+1 - k;
j = I[j];
}
if(j == n+1) break;
}
for(int i = 1; i <= n; i++){
if(s[i] == 'J'){
J[i] = i;
}else{
J[i] = J[i-1];
}
}
for(int i = n; i >= 1; i--){
if(s[i] == 'J'){
J[i] = J[i-1];
}
}
cnt = 0;
j = -1;
for(int i = n; i >= 1; i--){
if(s[i] == 'J'){
cnt++;
if(cnt == k){
j = i;
break;
}
}
}
if(j == -1){
cout << -1;
return;
}
vector<int> pfJ(n+2, INF);
for(int i = n; i >= 1; i--){
if(s[i] == 'J'){
pfJ[i] = i-j+1 - k;
j = J[j];
}
if(j == 0) break;
}
int ans = INF;
for(int i = 1; i <= n; i++){
if(s[i] == 'O'){
if(pfO[i] == INF) continue;
ans = min(ans, pfJ[J[i]] + pfO[i] + pfI[I[OO[i]]]);
}
}
if(ans == INF) ans = -1;
cout << ans;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
344 KB |
Output is correct |
2 |
Incorrect |
1 ms |
344 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
344 KB |
Output is correct |
2 |
Incorrect |
1 ms |
344 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
344 KB |
Output is correct |
2 |
Incorrect |
1 ms |
344 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |