编程练习——堆heap
因为vs2005中c++的Heap构造有些问题,所以才重写了heap类。
不知道vs2008中这个是不是个bug。
- /*createdbychicochen
- *date2008/10/25
- */
- template<classT,classCmp>
- classHeap
- {
- private:
- vector<T>heap;
- voidShiftDown(intindex)
- {
- while(!IsLeaf(index))
- {
- intl=Lchild(index);
- intr=Rchild(index);
- if(r!=-1)
- {
- if(Cmp::Up(heap[r],heap[l]))
- {
- //puttheupnodetotheleft
- swap(heap[l],heap[r]);
- }
- }
- if(Cmp::Up(heap[l],heap[index]))
- {
- //uptheleftchild
- swap(heap[l],heap[index]);
- index=l;
- }
- else
- {
- break;
- }
- }
- }
- voidShiftUp(intindex)
- {
- intparent=-1;
- while(index!=0)
- {
- parent=Parent(index);
- if(Cmp::Up(heap[index],heap[parent]))
- {
- swap(heap[index],heap[parent]);
- index=parent;
- }
- else
- {
- break;
- }
- }
- }
- voidReHeapAll()
- {
- for(inti=Parent(heap.size()-1);i>=0;i--)
- {
- ShiftDown(i);
- }
- }
- voidReHeapOne(intindex)
- //setonepriorandre-positiontheindexnode
- {
- Tdata=heap[index];
- ShiftDown(index);
- if(Cmp::Eq(data,heap[index]))
- {
- ShiftUp(index);
- }
- }
- intParent(intindex)
- //parentnodeoftheindexnode
- {
- return(index-1)/2;
- }
- intLchild(intindex)
- //Leftchildoftheindexnode
- {
- if(!IsLeaf(index))
- returnindex*2+1;
- return-1;
- }
- intRchild(intindex)
- //Rightchildoftheindexnode
- {
- if(!IsLeaf(index))
- {
- intr=index*2+2;
- if(r<heap.size())
- returnr;
- }
- return-1;
- }
- intIsLeaf(intindex)
- {
- assert(index<heap.size());
- if(heap.size()==1)
- returntrue;
- intlastNode=Parent(heap.size()-1);
- returnlastNode<index;
- }
- intFindData(T&data)
- {
- intlen=heap.size();
- for(inti=0;i<len;i++)
- {
- if(Cmp::Eq(data,heap[i]))
- {
- returni;
- }
- }
- return-1;//cannotfindthedata
- }
- voidprintTree(intindex,intcount)
- {
- if(index<heap.size()&&index>=0)
- {
- printTree(Rchild(index),count+4);
- for(inti=0;i<count;i++)
- {
- cout<<"";
- }
- cout<<heap[index]<<endl;
- printTree(Lchild(index),count+4);
- }
- }
- public:
- Heap()
- {
- heap=vector<T>();
- }
- ~Heap()
- {
- //heapdestroyed
- }
- boolIsEmpty()
- {
- returnheap.size()==0;
- }
- voidInsert(T&data)
- {
- heap.push_back(data);
- ShiftUp(heap.size()-1);
- }
- voidDelete(intindex)
- {
- intlast=heap.size()-1;
- if(index>=0&&index<=last)
- {
- swap(heap[index],heap[last]);
- heap.pop_back();
- ReHeapOne(index);
- }
- }
- voidDelete(T&data)
- {
- intindex=FindData(data);
- if(index!=-1)
- Delete(index);
- }
- voidRemoveTop()
- {
- if(!IsEmpty()&&heap.size()>1)
- {
- swap(heap[0],heap[heap.size()-1]);
- heap.pop_back();
- ShiftDown(0);
- }
- elseif(heap.size()==1)
- {
- heap.pop_back();
- }
- }
- T&Top()
- {
- returnheap[0];
- }
- voidPrint()
- {
- printTree(0,1);
- }
- };