Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.2 kB
2
Indexable
Never
#include<vector>
#include<queue>

class node{
    public:
    int data;
    int i;
    int j;
    node(int val,int row,int col){
        this->data=val;
        i=row;
        j=col;
    }
};

class compare {
    public:
    bool operator()(node* a, node* b)  {
        return a->data > b->data;
    }
};


vector<int> mergeKSortedArrays(vector<vector<int>>&kArrays, int k)//jeta theke ber korchi sei array
//tar next element min heap e debo
{
    vector<int> ans;
    priority_queue<node* ,vector<node*>,compare> pq;

    for(int i=0;i<k;i++){
        node* tmp= new node(kArrays[i][0],i,0);
        pq.push(tmp);
    }

    while(pq.size()>0){
        node* top=pq.top(); //finding the lowest element from pq
        int i=top->i;
        int j=top->j;

        pq.pop();
        ans.push_back(top->data);  //puttig this lowest element into the answer
            if(j+1<kArrays[i].size()){
            int nextval=kArrays[i][j+1];//pushing the next element from this same array into the priority queue
            node* next=new node(nextval,i,j+1);
            pq.push(next);
        }
    }
    return ans;
}