Cod sursa(job #475667)

Utilizator andra23Laura Draghici andra23 Data 7 august 2010 21:54:10
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include<iostream>
#include<fstream>
#include<unistd.h>
#define MAX 200010

using namespace std;

int h[MAX], pos[MAX], a[MAX], n, l;
ofstream g;

void afisare();

void shift(int k){
    int aux, son, i;
    do {
        son = 0;
        if (k*2 <= l){
            son = k*2;
            if (k*2+1 <= l && a[h[k*2]] > a[h[k*2+1]])
                son = k*2+1;
            if (a[h[k]] <= a[h[son]])
                son = 0;
        }
        if (son){
            pos[h[son]] = k;
            pos[h[k]] = son;
            aux = h[son];
            h[son] = h[k];
            h[k] = aux;
            k = son;
        }    
    } while (son);
}

void percolate(int k){
    int key = h[k];
    while (k > 1 && a[h[k/2]] > a[key]){
        pos[h[k/2]] = k;
        h[k] = h[k/2];
        k = k/2;
    }
    h[k] = key; 
    pos[key] = k;
}

void extract(int k){
    h[k] = h[l];
    pos[h[k]] = k;
    l--;
    if (k > 1 && a[h[k]] < a[h[k/2]])
        percolate(k);
    else
        shift(k);
        
}

void afisare(){
    for (int i = 1; i <= l; i++)
        g<<a[h[i]]<<" ";
    g<<endl;
}

int main(){
    ifstream f("heapuri.in");
    g.open("heapuri.out");
    int i, t, type, info;
    f>>t;
    for (i = 1; i <= t; i++){
        f>>type;
        if (type == 1){
            f>>info;
            n++;
            a[n] = info;
            l++;
            h[l] = n;
            pos[n] = l;
            percolate(l);    
        } 
        else 
            if (type == 3){
                g<<a[h[1]]<<'\n';    
            }  
            else {
                f>>info;
                extract(pos[info]);    
            }
    }
    
    return 0;   
}