标签:
使用STL中priority_queue(由最大最小堆实现的)来实现。注意传递参数的时候需要传递三个。
模板声明:priority_queue<Type, Container, Functional>
这里的实现要求输入完全正确,所以代码移植性非常差。
#include <iostream> #include <algorithm> #include <queue> using namespace std; typedef struct { int key; int next; }Likelist; bool CompareLikelist(Likelist &i1,Likelist &i2){ return i1.key > i2.key; } void K_Merge(int *a,int *b, int n, int k){ priority_queue<Likelist,vector<Likelist>,decltype(CompareLikelist) *> pq(CompareLikelist); for (int i = 0; i < k; i++){ if (i > n - 1) pq.push({ INT_MAX, 0 }); else pq.push({ a[i], i + k }); } for (int i = 0; i < n; ++i){ Likelist temp = pq.top(); b[i] = temp.key; pq.pop(); if (temp.next>n - 1) pq.push({ INT_MAX, 0 }); else pq.push({ a[temp.next], temp.next + k }); } } int main(){ int a[10] = { 33,1, 8, 45, 2, 9, 67, 10,9, 666 }; int b[10]; K_Merge(a, b, 10, 3); for (auto r : b) cout << r << " "; }
标签:
原文地址:http://www.cnblogs.com/Nastukashii/p/4414349.html