Submission #888000

#TimeUsernameProblemLanguageResultExecution timeMemory
888000oviyan_gandhiJJOOII 2 (JOI20_ho_t2)C++17
100 / 100
12 ms8308 KiB
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int INF = 1e17;
typedef vector<int> vi; typedef vector<vector<int>> vvi;

typedef pair<int, int> pii;

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];
    vector<pii> jc;
    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.push_back({i, cost});
    }
    vi ic(n, INF); // cost if last I is at i
    d.clear(); cost = 0;
    for (int i = n-1; i >= 0; i--){
        if (i < n-1)
            ic[i] = ic[i+1];
        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] = min(ic[i], cost + i);
    }
    int ans = -1;
    for (auto [j, c] : jc){
        auto ptr = lower_bound(co.begin(), co.end(), co[j] + k);
        if (ptr == co.end()) break;
        int ci = ic[ptr-co.begin()];
        if (ci == INF) continue;
        int cost = ci + (c - j) - (k + 1);
        if (ans == -1 || cost < ans)
            ans = cost;
    }
    // if (co[i-1] - co[j] < k)
    //     continue;
    // int cost = (ci + i) + (cj - j) - (k + 1);
    
    cout << ans << endl;
    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...