Cod sursa(job #1122869)

Utilizator andreea_alexandraAndreea Alexandra andreea_alexandra Data 25 februarie 2014 21:01:17
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <cstdio>
#define MAX_N 200001
using namespace std;
int N, poz[MAX_N], heap[MAX_N], last=0, nr_ord[MAX_N], k=0;
FILE *f, *g;

void swap_val(int suc, int anc)
{
    int aux;
    aux=heap[suc];
    heap[suc]=heap[anc];
    heap[anc]=aux;
    aux=poz[nr_ord[suc]];
    poz[nr_ord[suc]]=poz[nr_ord[anc]];
    poz[nr_ord[anc]]=aux;
    aux=nr_ord[suc];
    nr_ord[suc]=nr_ord[anc];
    nr_ord[anc]=aux;
}

void insert_val(int x, int i)
{
    int loc;
    last++;
    heap[last]=x;
    loc=last;
    nr_ord[last]=i;
    poz[i]=last;
    if(last>1)
    {
        while(heap[loc/2]>x)
        {
            swap_val(loc, loc/2);
            loc=loc/2;
        }
    }
    poz[i]=loc;
    nr_ord[loc]=i;
}

void eliminate(int i)
{
    int
    index=poz[i];
    poz[i]=0;
    heap[index]=heap[last];
    nr_ord[index]=nr_ord[last];
    poz[nr_ord[last]]=index;
    last--;
    while(index*2<=last && (heap[2*index]<heap[index] || heap[2*index+1]<heap[index]))
    {
        if(heap[2*index]<heap[index])
        {
            swap_val(2*index, index);
            index=2*index;
        }
        else
            {
                swap_val(2*index+1, index);
                index=2*index+1;
            }

    }
}

int main()
{
    f = fopen("heapuri.in", "r");
    g = fopen("heapuri.out", "w");

    fscanf(f, "%d", &N);
    for(int i=0; i<N; i++)
    {
        int type, val;
        fscanf(f, "%d", &type);
        if(type==1)
        {
            k++;
            fscanf(f, "%d", &val);
            insert_val(val, k);
        }
        if(type==2)
        {
            fscanf(f, "%d", &val);
            eliminate(val);
        }
        if(type==3)
        {
            fprintf(g, "%d\n", heap[1]);
        }
    }

    fclose(f);
    fclose(g);
    return 0;
}