Cod sursa(job #755289)

Utilizator visanrVisan Radu visanr Data 5 iunie 2012 11:19:53
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.96 kb
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;

#define nmax 200010

int H[nmax], pos[nmax], N, cnt, M;

int father(int K) { return (K >> 1); }
int leftSon(int K) { return (K << 1); }
int rightSon(int K) { return ((K << 1) + 1); }


void sift(int N, int K)
{
     int son;
     cnt++;
     pos[cnt] = K;
     do
     {
         son = 0;
         if(leftSon(K) <= N)
         {
                       son = leftSon(K);
                       if(rightSon(K) <= N && H[rightSon(K)] < H[leftSon(K)]) son = rightSon(K);
                       if(H[son] >= H[K]) son = 0;
         }
         if(son)
         {
                swap(H[son], H[K]);
                K = son;
                pos[cnt] = K;
         }
     }while(son);
     cnt++;
}

void percolate(int N, int K)
{
     int key = H[K];
     while((K > 1) && (H[father(K)] > key))
     {
              H[K] = H[father(K)];
              K = father(K);
     }
     H[K] = key;
     pos[cnt++] = K;
}

void Cut(int &N, int K)
{
     H[K] = H[N];
     --N;
     if((K > 1) && (H[K] < H[father(K)])) percolate(N, K);
     else sift(N, K);
}

void Insert(int &N, int key)
{
     H[++N] = key;
     percolate(N, N);
}

int MaxValue() { return H[1]; }

int main()
{
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    int type, i, x, k;
    scanf("%i", &M);
    while(M --)
    {
              scanf("%i", &type);
              if(type == 1)
              {
                      scanf("%i", &x);
                      Insert(N, x);
              }
              if(type == 2)
              {
                      scanf("%i", &x);
                      int position = pos[x];
                      Cut(N, position);
              }
              if(type == 3)
              {
                      printf("%i\n", MaxValue());
              }
    }
    scanf("%i", &i);
    return 0;
}