Cod sursa(job #1052678)

Utilizator impulseBagu Alexandru impulse Data 11 decembrie 2013 17:46:02
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.91 kb
//
//  main.cpp
//  heapuri
//
//  Created by Alexandru Bâgu on 12/11/13.
//  Copyright (c) 2013 Alexandru Bâgu. All rights reserved.
//

#include <stdio.h>
#include <fstream>
using namespace std;

typedef struct node {
    int key, value;
} hnode;

typedef hnode* HEAP;

int n, KEY_ID;

int swap(hnode* h, hnode* h2)
{
    hnode aux = *h;
    *h = *h2;
    *h2 = aux;
    return 0;
}

int up(HEAP h, int p)
{
    while(p > 1 && h[p].value < h[p/2].value)
    {
        swap(h + p, h + p / 2);
        p/=2;//up(h, p / 2);
    }
    return 0;
}

int down(HEAP h, int p)
{
    int go = 1;
    while(n >= p * 2 && go)
    {
        go = 0;
        int p2 = p * 2;
        if(n > p2 && h[p2].value > h[p2 + 1].value)
            p2++;
        if(h[p].value > h[p2].value)
        {
            swap(h + p, h + p2);
            p = p2;
            go = 1;
            //down(h, p2);
        }
    }
    return 0;
}

int find_key(HEAP h, int i)
{
    int j;
    for(j = 1; j <= n; j++)
        if(h[j].key == i)
            return j;
    return -1;
}

int insert(HEAP h, int k)
{
    ++n;
    h[n].value = k;
    h[n].key = KEY_ID++;
    up(h, n);
    return 0;
}

int remove(HEAP h, int p)
{
    if(p <= 0) return 0;
    h[p] = h[n--];
    down(h, p);
    up(h, p);
    return 0;
}

int main(int argc, const char * argv[])
{
    const int MAX = 2000001;
    
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    
    int N;
    scanf("%d ", &N);
    HEAP H = new hnode[MAX];//malloc(MAX * sizeof(hnode));
    int i, k;
    n = 0;
    KEY_ID = 1;
    for(i = 1; i <= N; i++)
    {
        scanf("%d", &k);
        if(k == 1)
        {
            int a;
            scanf("%d", &a);
            insert(H, a);
        }
        else if(k == 2)
        {
            int a;
            scanf("%d", &a);
            remove(H, find_key(H, a));
        }
        else
            printf("%d \n", H[1].value);
    }
    return 0;
}