因为vs2005中c++的Heap构造有些问题,所以才重写了heap类。
不知道vs2008中这个是不是个bug。
- /* created by chico chen
- * date 2008/10/25
- */
- template<class T,class Cmp>
- class Heap
- {
- private:
- vector<T> heap;
- void ShiftDown(int index)
- {
- while(!IsLeaf(index))
- {
- int l = Lchild(index);
- int r = Rchild(index);
- if(r != -1)
- {
- if(Cmp::Up(heap[r],heap[l]))
- {
- // put the up node to the left
- swap(heap[l],heap[r]);
- }
- }
- if(Cmp::Up(heap[l],heap[index]))
- {
- // up the left child
- swap(heap[l],heap[index]);
- index = l;
- }
- else
- {
- break;
- }
- }
- }
- void ShiftUp(int index)
- {
- int parent = -1;
- while(index != 0)
- {
- parent = Parent(index);
- if(Cmp::Up(heap[index],heap[parent]))
- {
- swap(heap[index],heap[parent]);
- index = parent;
- }
- else
- {
- break;
- }
- }
- }
- void ReHeapAll()
- {
- for(int i=Parent(heap.size()-1); i>= 0; i--)
- {
- ShiftDown(i);
- }
- }
- void ReHeapOne(int index)
- // set one prior and re-position the index node
- {
- T data = heap[index];
- ShiftDown(index);
- if(Cmp::Eq(data,heap[index]))
- {
- ShiftUp(index);
- }
- }
- int Parent(int index)
- // parent node of the index node
- {
- return (index-1)/2;
- }
- int Lchild(int index)
- // Left child of the index node
- {
- if(!IsLeaf(index))
- return index*2+1;
- return -1;
- }
- int Rchild(int index)
- // Right child of the index node
- {
- if(!IsLeaf(index))
- {
- int r= index*2+2;
- if(r<heap.size())
- return r;
- }
- return -1;
- }
- int IsLeaf(int index)
- {
- assert(index < heap.size());
- if(heap.size() == 1)
- return true;
- int lastNode = Parent(heap.size()-1);
- return lastNode < index;
- }
- int FindData(T& data)
- {
- int len = heap.size();
- for(int i = 0; i < len; i++)
- {
- if(Cmp::Eq(data,heap[i]))
- {
- return i;
- }
- }
- return -1;// can not find the data
- }
- void printTree(int index,int count)
- {
- if(index < heap.size() && index >=0)
- {
- printTree(Rchild(index),count+4);
- for(int i = 0; i < count; i++)
- {
- cout << " ";
- }
- cout <<heap[index]<<endl;
- printTree(Lchild(index),count+4);
- }
- }
- public:
- Heap()
- {
- heap = vector<T>();
- }
- ~Heap()
- {
- // heap destroyed
- }
- bool IsEmpty()
- {
- return heap.size() == 0;
- }
- void Insert(T& data)
- {
- heap.push_back(data);
- ShiftUp(heap.size()-1);
- }
- void Delete(int index)
- {
- int last = heap.size()-1;
- if(index>=0 && index <= last)
- {
- swap(heap[index],heap[last]);
- heap.pop_back();
- ReHeapOne(index);
- }
- }
- void Delete(T& data)
- {
- int index = FindData(data);
- if(index != -1)
- Delete(index);
- }
- void RemoveTop()
- {
- if(!IsEmpty()&&heap.size()>1)
- {
- swap(heap[0],heap[heap.size()-1]);
- heap.pop_back();
- ShiftDown(0);
- }
- else if(heap.size() == 1)
- {
- heap.pop_back();
- }
- }
- T& Top()
- {
- return heap[0];
- }
- void Print()
- {
- printTree(0,1);
- }
- };