Cod sursa(job #634980)

Utilizator mr.johnFMI - Laceanu Ionut-Adrian mr.john Data 18 noiembrie 2011 03:20:26
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
#include <fstream>
#include <algorithm>

using namespace std;

int h[200001],v[200001],poz[200001]; 

inline int tata(int nod){
  return nod>>1;
}

inline int fiu_stang(int nod){
  return nod*2;
}

inline int fiu_drept(int nod){
  return nod*2+1;
}

//inline int min() {
// return v[h[1]];
//}

/*void afis_poz(int nr){
  cout<<"pozt ";
  for (int i=1; i<=nr;i++)
    cout<<poz[i]<<" ";
  cout<<endl;
}

void afis_heap(int n){
  cout<<"heap ";
  for (int i=1; i<=n;i++)
    cout<<v[h[i]]<<" ";
  cout<<endl;
}
*/

void cerne(int n, int k){
  int fiu;
  do {
    fiu=0;
    if (fiu_stang(k)<=n){
      fiu = fiu_stang(k);
      if (fiu_drept(k)<=n && v[h[fiu_drept(k)]]<v[h[fiu_stang(k)]]){
        fiu=fiu_drept(k);
      }
      if (v[h[fiu]]>=v[h[k]])
        fiu=0;
    }
    if (fiu){
      swap(h[k], h[fiu]);
      poz[h[k]]=k;
      poz[h[fiu]]=fiu;
      k=fiu;
    }
  } while (fiu);
}
      
void urca(int n, int k){
  int key = h[k],t;
  while ((k>1)&&(v[key]<v[h[tata(k)]])){
    t=tata(k);
    swap (h[k],h[t]);
    poz[h[k]]=k;
    poz[h[t]]=t;
    k=t;
    /*poz[h[t]]=poz[h[k]];
    h[k]=h[t];
    k=t;
    poz[key]=k;
    h[k]=key;*/
  }
}

//void build(int n){
//  for (int i=n/2; i>0; i--){
//    cerne(n,i);
//  }
//}

void sterge(int &n, int k){
/*  if (poz[k]){ */
    h[poz[k]]=h[n];
    poz[h[n]]=poz[k];
    int pp=poz[k];
    poz[k]=0;
    n--;
    if ((pp>1)&&(v[h[k]]<v[h[tata(k)]])){
      urca(n,pp);
    } else {
      cerne (n,pp);
    }
  //}
}

void insert(int &n, int &nr, int y){
  v[++nr]=y;
  h[++n]=nr;
  poz[nr]=n;
  urca(n,n);
}
  
//void heapsort(int n){
// for (int i=n;i>=2;i--){
//    swap(h[1],h[i]);
//    cerne(i-1,1);
//  }
//}

int main()
{
  ifstream fin("heapuri.in");
  ofstream fout("heapuri.out");
  int n=0,nr=0;
  int x,y,kp;
  int op;
  fin>>op;
  for (int i=1; i<=op;i++){
    fin>>x;
    if (x==1){
      fin>>y;
      insert(n,nr,y);
    }
    if (x==2){
      fin>>kp;
      sterge(n,kp);
    } 
    if (x==3)
      fout<<v[h[1]]<<"\n";
  }
  fin.close(); fout.close();
  return 0;
}