Cod sursa(job #2767430)

Utilizator tryharderulbrebenel mihnea stefan tryharderul Data 6 august 2021 10:32:13
Problema Heapuri Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.48 kb
#include <bits/stdc++.h>

using namespace std;

bool smaller(int a,int b) {
    return a < b;
}
template <typename T>
class heap {
private:
    vector<int> t;
    vector<int> poz; 
    vector<int> ind; 
    
    int parrent(int idx) {
        return idx/2;
    }
    bool (*comp)(T a, T b);
    int left_son(int idx) {
        return 2 * idx;
    }
    int right_son(int idx) {
        return 2 * idx + 1;
    }
    void upHeap(int idx) {
        while(idx > 1 && comp(t[idx], t[parrent(idx)]) ) {
            swap(t[parrent(idx)], t[idx]);
            poz[ind[idx]] = parrent(idx);
            poz[ind[parrent(idx)]] = idx;
            swap(ind[idx], ind[parrent(idx)] );
            idx = parrent(idx);        
        }

    }
    void downHeap(int idx) {
        // recursiv
        int best = idx;
        if(left_son(idx) <= size() && comp(t[left_son(idx)], t[best]) ) {
            best = left_son(idx);
        }
        if(right_son(idx) <= size() && comp(t[right_son(idx)],t[best] )) {
            best = right_son(idx);
        }
        if(best != idx) {
            swap(t[best], t[idx]);
            poz[ind[idx]] = parrent(idx);
            poz[ind[parrent(idx)]] = idx;
            swap(ind[idx], ind[parrent(idx)]);
            downHeap(best);
        }
    }
public:
    int size() {
        return t.size() - 1;
    }
    
    heap(bool (* f)(T a, T b) ) {
        t.resize(1);
        poz.resize(1);      
        ind.resize(1);      
        comp = f;
    }
    
    void insert(T val) {
        t.push_back(val);
        poz.push_back(size() );
        ind.push_back(ind.size() );
        upHeap(size());
    }
    
    void del(int x) {
		swap(t[poz[x]], t[size()]);
		poz[ind[size()]] = poz[x];
		ind[poz[x]] = ind[size()];
		t.pop_back();
		downHeap(poz[x]);
		upHeap(poz[x]);
		
	}
	
	void afis() { // DEBUGGING
		for(int i = 1; i <= size(); i++) {
			printf("%d %d %d\n",t[i],poz[i],ind[i] );
		}
	}
    
    T top() {
        return t[1];
    }

};


int main() {
	freopen("heapuri.in","r",stdin);
	freopen("heapuri.out","w",stdout);
	int t;
	scanf("%d",&t);
	heap<int> h(smaller);
	while(t--) {
		int type;
		scanf("%d",&type);
		if(type == 1) {
			int x;
			scanf("%d",&x);
			h.insert(x);
		}else if(type == 2) {
			int x;
			scanf("%d",&x);
			h.del(x);
		}else {
			printf("%d\n",h.top() );
		}
	}
	//~ h.insert(4);
	//~ h.insert(7);
	//~ h.insert(9);
	//~ printf("%d\n",h.top());
	//~ h.insert(2);
	//~ h.del(1);
	//~ printf("%d\n",h.top());
	//~ h.del(4);
	//~ printf("%d\n",h.top());
	
	return 0;
}