您的位置:首页 > 运维架构

最小优先队列 解决TopK问题

2015-08-21 21:46 357 查看
#include <vector>
#include <algorithm>
#include <limits>
#include <iostream>
using namespace std;

//////// 优先队列
#define  MAX_HEAP    300
class PriorityHeap
{
public:
PriorityHeap();
~PriorityHeap();

bool  empty();
int   size();
int   top();
void  push(int nValue);
int   pop();
private:
int				GetParentIndex(int nIndex);
const int&		GetParentValue(int nIndex);
int             GetLeftIndex(int nIndex);
int             GetRightIndex(int nIndex);
void            AdjustHeap(int nIndex);               // 调整根节点为nIndex的子树  前提是left(nIndex) right(nIndex)都是大顶堆

int  heap[MAX_HEAP];
int  heapSize;
};

PriorityHeap::PriorityHeap()
{
memset(heap, 0, sizeof(heap));
heapSize = 0;
}

PriorityHeap::~PriorityHeap()
{

}

bool PriorityHeap::empty()
{
return heapSize > 0 ? false : true;
}

const int& PriorityHeap::GetParentValue(int nIndex)
{
if (nIndex < 0 || nIndex >= heapSize)
{
return 0;
}

int nParentIndex = GetParentIndex(nIndex);
return heap[nParentIndex];
}

int PriorityHeap::GetParentIndex(int nIndex)
{
//return nIndex/2 - 1 > 0 ? nIndex/2 - 1 : 0;
return (nIndex+1)/2 - 1;
}

int PriorityHeap::GetLeftIndex(int nIndex)
{
return 2*nIndex + 1;
}

int PriorityHeap::GetRightIndex(int nIndex)
{
return 2*nIndex + 2;
}

void PriorityHeap::push(int nValue)
{
heapSize = heapSize + 1;
int heapIndex = heapSize -1;

heap[heapIndex] = nValue;
int nParentIndex = GetParentIndex(heapIndex);
while(heapIndex > 0 && heap[nParentIndex] > heap[heapIndex])
{
int nTemp = heap[heapIndex];
heap[heapIndex] = heap[nParentIndex];
heap[nParentIndex] = nTemp;

heapIndex = nParentIndex;
nParentIndex = GetParentIndex(heapIndex);
}
}

int PriorityHeap::top()
{
return heap[0];
}

int PriorityHeap::size()
{
return heapSize;
}

int PriorityHeap::pop()
{
int nRoot = heap[0];
heapSize = heapSize - 1;
heap[0] = heap[heapSize];
AdjustHeap(0);
return nRoot;
}

void PriorityHeap::AdjustHeap(int nIndex)
{
int largestIndex = nIndex;
int leftIndex = GetLeftIndex(nIndex);
int rightIndex = GetRightIndex(nIndex);

if (leftIndex < heapSize && heap[leftIndex] < heap[largestIndex])
{
largestIndex = leftIndex;
}

if (rightIndex < heapSize && heap[rightIndex] < heap[largestIndex])
{
largestIndex = rightIndex;
}

if (largestIndex != nIndex)
{
int nTemp = heap[largestIndex];
heap[largestIndex] = heap[nIndex];
heap[nIndex] = nTemp;
AdjustHeap(largestIndex);
}
}

void FindTopK()
{
int nValue;
int k;
PriorityHeap heap;

cin >> k;
while (cin >> nValue)
{
if (heap.size() < k)
{
heap.push(nValue);
}
else if(nValue > heap.top())
{
heap.pop();
heap.push(nValue);
}
}
while(!heap.empty())
{
cout << heap.pop() << " " << endl;
}
system("pause");
}

int main()
{
PriorityHeap  Heap;
int nValue;
while (cin >> nValue)
{
Heap.push(nValue);
}

while(!Heap.empty())
{
cout << Heap.pop() << " " << endl;
}

FindTopK();
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: