Pagini recente » Cod sursa (job #2788226) | Cod sursa (job #345719) | Cod sursa (job #1160360) | Cod sursa (job #1299398) | Cod sursa (job #3125069)
#include <vector>
#include <fstream>
//#include <iostream>
//using namespace std;
std::ifstream cin("mergeheap.in");
std::ofstream cout("mergeheap.out");
class node{
std::vector<node*> childs;
int val;
public:
node(int x):val(x){}
void addchild(node* n){
childs.push_back(n);
}
std::vector<node*> getChilds(){return childs;}
int getVal(){
return val;
}
bool hasChilds(){return !childs.empty();}
};
class pheap{
node *root;
public:
pheap(int x):root(new node(x)){}
pheap():root(nullptr){};
node* getRoot(){return root;}
void setRoot(node* rt){root = rt;}
void push(int val){
if(root == nullptr){
root = new node(val);
return;
}
if(root->getVal()>val){
root->addchild(new node(val));
return;
}
if(root->getVal()<=val){
node *rad = new node(val);
rad->addchild(root);
root = rad;
return;
}
}
static node * merge_pairs(std::vector<node *> &chd){
if(chd.size()==1)return chd[0];
if(chd[0]->getVal()>chd[1]->getVal()){
chd[0]->addchild(chd[1]);
}
else{
chd[1]->addchild(chd[0]);
chd[0] = chd[1];
}
chd.erase(chd.begin()++);
merge_pairs(chd);
return chd[0];
}
int toppop(){
int aux = root->getVal();
std::vector<node *> chd = root->getChilds();
setRoot(merge_pairs(chd));
return aux;
}
void merge(pheap B){
if(B.getRoot()== nullptr)return;
if(root == nullptr){
root = B.getRoot();
B.setRoot(nullptr);
return;
}
if(root->getVal()>B.getRoot()->getVal()){
root->addchild(B.getRoot());
B.setRoot(nullptr);
return;
}
if(root->getVal()<=B.getRoot()->getVal()){
B.getRoot()->addchild(root);
root = B.getRoot();
B.setRoot(nullptr);
return;
}
}
};
int main() {
int n,q;
cin>>n>>q;
pheap *h = new pheap[n];
for(int i=0;i<q;i++){
int querry;
cin>>querry;
switch(querry){
case 1:{
int m,x;
cin>>m>>x;
h[m-1].push(x);
break;
}
case 2:{
int m;
cin>>m;
cout<<h[m-1].toppop()<<"\n";
break;
}
case 3:{
int a,b;
cin>>a>>b;
h[a-1].merge(h[b-1]);
break;
}
default:{}
}
}
return 0;
}