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;
template<typename T>
void out(T x) { cout << x << endl; exit(0); }
#define watch(x) cout << (#x) << " is " << (x) << endl
using ll = long long;
const int maxn = 1e6 + 5;
int n,k;
string s;
int a[maxn];
int acc[maxn][3];
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin>>n>>k;
cin>>s;
for (int i=0; i<n; i++) {
if (s[i]=='J') {
a[i+1]=0;
} else if (s[i]=='O') {
a[i+1]=1;
} else if (s[i]=='I') {
a[i+1]=2;
} else assert(false);
}
for (int i=1; i<=n; i++) {
acc[i][a[i]]++;
for (int j=0; j<3; j++) {
acc[i][j] += acc[i-1][j];
}
}
auto qry = [&](int l, int r, int i) {
return acc[r][i] - acc[l-1][i];
};
int res = 2*n;
for (int i=1; i<=n; i++) {
if (a[i]==1) {
if (qry(1,i,0)<k || qry(i,n,1)<k || qry(1,n,2)<k) {
continue;
}
int L = -1, R = -1;
// reach back for J
{
int lo = 1;
int hi = i+1;
while (hi-lo>1) {
int mid=(lo+hi)/2;
if (qry(mid,i,0)>=k) {
lo = mid;
} else {
hi = mid;
}
}
L = lo;
}
int I = -1;
// find kth I
{
int lo = i-1;
int hi = n;
while (hi-lo>1) {
int mid=(lo+hi)/2;
if (qry(i,mid,1)>=k) {
hi = mid;
} else {
lo = mid;
}
}
I = hi;
}
if (qry(I,n,2)<k) {
continue;
}
// find kth O
{
int lo = I-1;
int hi = n;
while (hi-lo>1) {
int mid=(lo+hi)/2;
if (qry(I,mid,2)>=k) {
hi = mid;
} else {
lo = mid;
}
}
R = hi;
}
// watch(i);
// cout<<L<<" "<<I<<" "<<R<<endl;
int cur = (R-L+1) - 3*k;
res = min(res, cur);
}
}
if (res>n) res=-1;
cout<<res<<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... |