1345 — D Educational Codeforces Round 87 (Rated for Div. 2), problem: (D) Multiset

Revision en1, by kernelpanic77, 2020-05-21 19:52:26
#include<bits/stdc++.h>
#define MAX 1000006
typedef long long int ll;
using namespace std;

int fenwick[MAX], arr[MAX], n;

void update(ll x, ll delta){
    for(;x<=n;x+=x&-x){
        fenwick[x] += delta;
    }
}

int query(int x){
    int sum = 0;
    for(;x>0;x-=(x&-x)){
        sum += fenwick[x];
    }
    return sum;
}

int element_idx(int rank){
    int l=1, r = n;
    int idx = MAX;
    while(l<=r){
        int mid = (l+r)/2;
        if(query(mid)>=rank){
            idx = min(idx, mid);
            r = mid -1;
        }
        else{
            l =  mid + 1;
        }
    }
    return idx;
}

int main(){
    int q;
    cin >> n >> q;
    for(int i=1;i<=n;i++){
        cin >> arr[i];
        update(arr[i], 1);
    }
    int i;
    while(q--){
        cin >> i;
        if(i>0){
            update(i, 1);
        }
        else{
            i = abs(i);
            i = element_idx(i);
            update(i, -1);
        }
    }
    int final = element_idx(1);
    if(final == MAX){
        printf("%d", 0);
    }
    else{
        printf("%d", final);
    }
    return 0;
}

Guys my code is continuously getting TLE on Test case 6. Can someone pls help find the bug

Tags #binary search, #fenwick tree, education round 87, #multiset

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English kernelpanic77 2020-05-21 20:06:02 1240
en1 English kernelpanic77 2020-05-21 19:52:26 1347 Initial revision (published)