使用堆合并K个排序的数组

时间:2019-09-27 11:11:02

标签: c++ heap

我已经编写了这段代码,但是遇到编译错误并且无法发现它。代码说明: 一类存储数据以及X轴和Y轴地址。创建第二类只是为了制造函子。 首先,我创建一个大小为K的MinHeap,然后弹出最小元素并将其存储在最终答案中:

#include<iostream>
#include<queue>
#include<vector>
#include<climits>
using namespace std;
class HeapNode{
    public:
        long long int data;
        int addressX;
        int addressY;
        HeapNode(long long int  d,int aX,int aY){
            data=d;
            addressX=aX;
            addressY=aY;
        }
};
class NodeCompare{
    public:
        bool operator()(HeapNode A,HeapNode B){
            return A.data<B.data;
        }
};
int main() {
    int n,k;
    cin>>k>>n;
    long long arr[k][n];
    for(int i=0;i<k;i++){
        for(int j=0;j<n;j++)
            cin>>arr[i][j];
    }
    int i=0;
    vector <long long int> ans;
    ans.reserve(n*k);
    priority_queue<HeapNode,vector<HeapNode>,greater<NodeCompare>> pq;
    for(int j=0;j<k;j++){
            HeapNode H(arr[j][i],j,i);
            pq.push(H);
        }
        HeapNode check=pq.top();
    while(check.data!=INT_MAX){
        HeapNode temp=pq.top();
        pq.pop();
        ans[i]=temp.data;
        i++;
        int x=temp.addressX;
        int y=temp.addressY + 1;
        if(y==n-1){
            HeapNode inp(INT_MAX,x,y);
             pq.push(inp);
        }else{
            HeapNode inp(arr[x][y+1],x,y);
        pq.push(inp);
       } check=pq.top();
    }
    i=0;
    while(i<n*k){
        cout<<ans[i]<<" ";
        i++;
    }
    return 0;
}

编译错误为:

  

编译失败,退出代码为1,编译器输出:在/usr/include/c++/7/bits/stl_algobase.h:71:0包含的文件中,/ usr / include / c ++ / 7 / bits / char_traits.h :39,来自/ usr / include / c ++ / 7 / ios:40,来自/ usr / include / c ++ / 7 / ostream:38,来自/ usr / include / c ++ / 7 / iostream:39,来自prog.cpp: 1:/ usr / include / c ++ / 7 / bits / predefined_ops.h:在'bool __gnu_cxx :: __ ops :: _ Iter_comp_val <_Compare> :: operator()(_ Iterator,_Value&)[带有_Iterator = __gnu_cxx –

0 个答案:

没有答案