/ SeriousOJ /

Record Detail

Time Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 532.0 KiB
#2 Accepted 1ms 532.0 KiB
#3 Accepted 260ms 4.52 MiB
#4 Accepted 1ms 532.0 KiB
#5 Accepted 1ms 532.0 KiB
#6 Accepted 324ms 4.633 MiB
#7 Accepted 64ms 4.562 MiB
#8 Accepted 67ms 4.816 MiB
#9 Time Exceeded ≥2598ms ≥5.727 MiB
#10 Time Exceeded ≥2599ms ≥5.156 MiB

Code

#include<bits/stdc++.h>

using namespace std;
#define ll long long int 

const int MAXN = 200005;
const int SQRTN = 250;  

bool ar[200007];
vector<ll>p;

//Mo's Algorithm 

struct Query {
    int l, r, idx;
};

vector<int> ans;
vector<int> arr;
vector<Query> queries;
ll frequency[MAXN]; 
map<int, int> countMap; 
int threshold;


bool compare(const Query &a, const Query &b) {
    int block_a = a.l / SQRTN;
    int block_b = b.l / SQRTN;
    if (block_a != block_b)
        return block_a < block_b;
    return (block_a % 2 == 0) ? (a.r < b.r) : (a.r > b.r);
}


void add(int position, int threshold) {
    int element = arr[position];
    countMap[element]++;
    if (countMap[element] > threshold) {
        frequency[element]++;  
    }
}


void remove(int position, int threshold) {
    int element = arr[position];
    if (countMap[element] > threshold) {
        frequency[element]--;
    }
    countMap[element]--;
}


int get_min_valid_candidate(int threshold) {
    int min_candidate = -1;
    for (const auto &entry : countMap) {
        int element = entry.first;
        if (entry.second > threshold && (min_candidate == -1 || element < min_candidate)) {
            min_candidate = element;
        }
    }
    return min_candidate;
}


void process_queries(int n, int q) {
    int L = 0, R = -1;
    for (Query &query : queries) {
        int l = query.l - 1, r = query.r - 1; 

    
        threshold = (r - l + 1) / 3;

      
        while (R < r) add(++R, threshold);
        while (R > r) remove(R--, threshold);

        
        while (L < l) remove(L++, threshold);
        while (L > l) add(--L, threshold);

        
        ans[query.idx] = get_min_valid_candidate(threshold);
    }
}

int main() {
    
    
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    
    
    int n, q;
    cin >> n >> q;
    arr.resize(n);
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }

    queries.resize(q);
    ans.resize(q, -1);

    for (int i = 0; i < q; i++) {
        int l, r;
        cin >> l >> r;
        queries[i] = {l, r, i};
    }

    
    sort(queries.begin(), queries.end(), compare);

    
    process_queries(n, q);

    
    for (int i = 0; i < q; i++) {
        cout << ans[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:42:03
Judged At
2024-11-05 16:42:03
Judged By
Score
40
Total Time
≥2599ms
Peak Memory
≥5.727 MiB