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 <bits/stdc++.h>
using namespace std;
#define int long long
typedef vector<int> vi; typedef vector<vector<int>> vvi;
int32_t main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, k; cin >> n >> k;
string s; cin >> s;
vi bo(n), ao(n), co(n); // nearest O before i, nearest O after i, count of O
bo[0] = (s[0] == 'O') - 1;
co[0] = (s[0] == 'O');
for (int i = 1; i < n; i++){
bo[i] = (s[i] == 'O') ? i : bo[i-1];
co[i] = co[i-1] + (s[i] == 'O');
}
ao[n-1] = (s[n-1] == 'O') ? n-1 : -1;
for (int i = n-2; i >= 0; i--)
ao[i] = (s[i] == 'O') ? i : ao[i+1];
vi jc(n, -1); // cost if last J is at i
deque<int> d; int cost = 0;
for (int i = 0; i < n; i++){
if (s[i] != 'J') continue;
if (!d.empty())
cost += i - d.back() - 1;
d.push_back(i);
if ((int)d.size() == k+1){
int f = d.front();
d.pop_front();
cost -= d.front() - f - 1;
}
if ((int)d.size() == k)
jc[i] = cost;
}
vi ic(n, -1); // cost if last I is at i
d.clear(); cost = 0;
for (int i = n-1; i >= 0; i--){
if (s[i] != 'I') continue;
if (!d.empty())
cost += d.back() - i - 1;
d.push_back(i);
if ((int)d.size() == k+1){
int f = d.front();
d.pop_front();
cost -= f - d.front() - 1;
}
if ((int)d.size() == k)
ic[i] = cost;
}
int ans = -1;
for (int i = 0; i < n; i++){
if (jc[i] == -1) continue;
for (int j = i+2; j < n; j++){
if (ic[j] == -1 || co[j-1] - co[i] < k) continue;
int cost = jc[i] + ic[j] + (j - i - 1 - k);
if (ans == -1 || ans > cost)
ans = cost;
}
}
cout << ans << endl;
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... |