This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#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();
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |