Cod sursa(job #3178749)

Utilizator paull122Paul Ion paull122 Data 2 decembrie 2023 13:10:40
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
#define MOD 666013

struct node
{
    int val,id;
};
inline int leftchild(int i)
{
    return i*2+1;
}
inline int rightchild(int i)
{
    return i*2+2;
}
inline int parent(int i)
{
    return (i-1)/2;
}

int pos[200001];
node heap[200001];
int heapsize;

void upheap(int i)
{
    if(i && heap[parent(i)].val >= heap[i].val)
    {
        pos[heap[i].id]=parent(i);
        pos[heap[parent(i)].id]=i;
        swap(heap[i],heap[parent(i)]);
        upheap(parent(i));
    }
}
void downheap(int i)
{
    int j=i;
    int left=leftchild(i),right = rightchild(i);
    if(left <= heapsize && heap[left].val <= heap[j].val)
    {
        j=left;
    }
    if(right <= heapsize && heap[right].val <= heap[j].val)
    {
        j = right;
    }
    if(i!=j)
    {
        pos[heap[i].id]=j;
        pos[heap[j].id]=i;
        swap(heap[i],heap[j]);
        downheap(j);
    }
}
void insheap(node i)
{
    heap[heapsize++]=i;
    pos[i.id]=heapsize-1;
    upheap(heapsize-1);
}

void remheap(int i)
{
    i = pos[i];
    heap[i]=heap[heapsize-1];
    pos[heap[heapsize-1].id]=i;
    heapsize--;

    downheap(i);
    upheap(i);
}
void dfs(int i)
{
    cout << heap[i].val << " ";
    if(rightchild(i) < heapsize)
    {
        dfs(rightchild(i));
    }
    if(leftchild(i) < heapsize)
    {
        dfs(leftchild(i));
    }
}
bool isnum(char x)
{
    return x >='0' && x<='9';
}
ll mx(ll a,ll b)
{
    return a > b ? a : b;
}
int main()
{
    int q;
    fin >> q;
    int k=1;
    while(q--)
    {
        int t,x;
        fin >> t;
        if(t==1 )
        {
            fin >> x;
            insheap({x,k++});
        }
        if(t==2)
        {
            fin >> x;
            remheap(x);
        }
        if(t==3)
        {
            fout << heap[0].val << "\n";
        }
    }
}