/ SeriousOJ /

Record Detail

Time Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 396.0 KiB
#2 Accepted 1ms 532.0 KiB
#3 Time Exceeded ≥2600ms ≥4.891 MiB
#4 Accepted 1ms 532.0 KiB
#5 Accepted 1ms 532.0 KiB
#6 Time Exceeded ≥2596ms ≥4.93 MiB

Code

#include <bits/stdc++.h>
using namespace std;

struct Query {
    int l, r, idx;
    Query(int left, int right, int index) : l(left), r(right), idx(index) {}
};

// Custom comparator for sorting queries in Mo's order
bool compareQueries(const Query &a, const Query &b) {
    static int blockSize = sqrt(200000); // √(max N)
    if (a.l / blockSize != b.l / blockSize)
        return a.l < b.l;
    return (a.l / blockSize % 2 == 0) ? (a.r < b.r) : (a.r > b.r);
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int N, Q;
    cin >> N >> Q;
    vector<int> A(N);
    for (int i = 0; i < N; ++i) {
        cin >> A[i];
    }

    vector<Query> queries;
    for (int i = 0; i < Q; ++i) {
        int l, r;
        cin >> l >> r;
        queries.emplace_back(l - 1, r - 1, i); // Convert 1-based index to 0-based
    }

    // Sort queries based on Mo's algorithm ordering
    sort(queries.begin(), queries.end(), compareQueries);

    vector<int> answer(Q, -1);
    vector<int> freq(N + 1, 0); // Frequency of each element in the current range
    int currentL = 0, currentR = -1;

    auto add = [&](int pos) {
        int val = A[pos];
        freq[val]++;
    };

    auto remove = [&](int pos) {
        int val = A[pos];
        freq[val]--;
    };

    for (const auto& q : queries) {
        int left = q.l;
        int right = q.r;
        int threshold = (right - left + 1) / 3;

        // Extend the range to [left, right]
        while (currentR < right) add(++currentR);
        while (currentR > right) remove(currentR--);
        while (currentL < left) remove(currentL++);
        while (currentL > left) add(--currentL);

        // Find the minimum value satisfying the frequency condition
        int minValue = INT_MAX;
        for (int i = 1; i <= N; ++i) {
            if (freq[i] > threshold) {
                minValue = min(minValue, i);
            }
        }

        answer[q.idx] = (minValue == INT_MAX) ? -1 : minValue;
    }

    // Output results for each query
    for (int i = 0; i < Q; ++i) {
        cout << answer[i] << '\n';
    }

    return 0;
}

Information

Submit By
Type
Submission
Problem
P1103 The Secret Garden of Numbers
Contest
Brain Booster #7
Language
C++17 (G++ 13.2.0)
Submit At
2024-11-05 16:15:24
Judged At
2024-11-05 16:15:24
Judged By
Score
20
Total Time
≥2600ms
Peak Memory
≥4.93 MiB