Cod sursa(job #3125064)

Utilizator stefanmo03Mocanu Stefan stefanmo03 Data 1 mai 2023 17:24:03
Problema Heapuri cu reuniune Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.55 kb
#include <vector>
#include <fstream>

std::ifstream cin("mergeheap.in");
std::ofstream cout("mergeheap.in");

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);
    }
    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>B.getRoot()){
            root->addchild(B.getRoot());
            B.setRoot(nullptr);
            return;
        }
        if(root<=B.getRoot()){
            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;
                h[a-1].merge(h[n-1]);
                break;
            }
            default:{}
        }
    }
    return 0;
}