Cod sursa(job #475641)

Utilizator andra23Laura Draghici andra23 Data 7 august 2010 19:58:13
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 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 shift(int k){
    int aux, son, i;
    do {
        son = 0;
        if (k*2 <= n){
            son = k*2;
            if (k*2+1 <= n && 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];
    int ord = 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[ord] = k;
}

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

void afisare(){
    for (int i = 1; i <= n; 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]);    
            }
    //afisare();
    }
    
    return 0;   
}