ENG  RUSTimus Online Judge
Online Judge
Problems
Authors
Online contests
About Online Judge
Frequently asked questions
Site news
Webboard
Links
Problem set
Submit solution
Judge status
Guide
Register
Update your info
Authors ranklist
Current contest
Scheduled contests
Past contests
Rules
back to board

Discussion of Problem 1126. Magnetic Storms

Solution using SQRT_DECOMPOSITION
Posted by iOli 19 Apr 2018 22:18
#include <bits/stdc++.h>
using namespace std;

int query(int l, int r, vector<int> bucket, vector<int> v) {
    int n = v.size();
    int bkt_sz = sqrt(n);
    int bkts = bucket.size();

    int lb = l/bkt_sz;
    int rb = r/bkt_sz;
    int lbp = l%bkt_sz;
    int rbp = r%bkt_sz;


    int retval = -1;

    if (lb == rb) {
        for (int i=lb*bkt_sz+lbp; i <= lb*bkt_sz+rbp; i++)
            retval = max(retval, v[i]);
        return retval;
    }

    for (int i=lb+1; i < rb; i++)
        retval = max(retval, bucket[i]);

    for (int i=lb*bkt_sz+lbp; i<n; i++) {
        if (i >= (lb+1)*bkt_sz) break;
        retval = max(retval, v[i]);
    }

    for (int i=rb*bkt_sz; i <= rb*bkt_sz+rbp; i++) {
        retval = max(retval, v[i]);
    }

    return retval;
}

int main() {

    int k;
    cin >> k;

    vector<int> v;

    while (true) {
        int a;
        cin >> a;
        if (a == -1) break;
        v.push_back(a);
    }

    int n = v.size();
    int bkt_sz = sqrt(n);

    vector<int> bucket;

    int count = bkt_sz;
    int max_value = -1;
    for (int i=0; i<n; i++) {
        if (count == 0) {
            count = bkt_sz;
            bucket.push_back(max_value);
            max_value = -1;
        }
        count -= 1;
        max_value = max(max_value, v[i]);
    }

    bucket.push_back(max_value);

    for (int i=0; i+k-1 < n; i++) {
        cout << query(i, i+k-1, bucket, v) << endl;
    }

}

Edited by author 19.04.2018 22:19