博客首页 注册 建议与交流 排行榜 加入友情链接
推荐 投诉 搜索: 帮助

寻路

摄心为纲, 断惑为要, 常行惭愧, 常观己心.
   linfengfeiye.cublog.cn
关于作者  
姓名:秒振
职业:计算机
年龄:28
位置:
个性介绍:

我的分类  




最小堆队列实现
#include <iostream>
using namespace std;
enum Result{Overflow,Underflow};
template <class T>
class PrioQueue
{
public:
 PrioQueue()
 {
  maxSize=20;
  n=0;
  q=new T[maxSize];
 }
 PrioQueue(T* head,int length)
 {
  maxSize=length+1;
  n=length;
  q=new T[length];
  for(int i=0;i<length;i++)
   q[i]=head[i];
        CreateHeap(length);
 }
 ~PrioQueue(){delete q;}
    void Append(const T& x);
 void Serve(T& x);
 bool IsEmpty() const
 {
  return n==0;
 }
 bool IsFull() const
 {
  return n==20;
 }
private:
 T* q;
 void AdjustDown(int r,int j);
 void AdjustUp(int j);
 void CreateHeap(int n);
// void Print();
 int n,maxSize;
};
template <class T>
void PrioQueue<T>::AdjustDown(int r,int j)
{
T temp=q[r];
int m=2*r+1;
while(m<=j)
{
if((q[m]>q[m+1])&&(m<j))
m=m+1;
if(temp>q[m])
q[(m-1)/2]=q[m];
m=2*m+1;
}
q[(m-1)/2]=temp;
}
template <class T>
void PrioQueue<T>::AdjustUp(int j)
{
T temp=q[j];
int m=j;
while((m>0)&&(q[(m-1)/2]>temp))
{
q[m]=q[(m-1)/2];
m=(m-1)/2;
}
q[m]=temp;
}
template <class T>
void PrioQueue<T>::Serve(T& x)
{
if(IsEmpty()) throw Overflow;
x=q[0];
q[0]=q[n-1];
AdjustDown(0,n-1);
n=n-1;
}
template <class T>
void PrioQueue<T>::Append(const T& x)
{
if(IsFull()) throw Underflow;
q[n++]=x;
AdjustUp(n-1);
//Print();
}
template <class T>
void PrioQueue<T>::CreateHeap(int n)
{
for(int i=(n-1)/2;i>-1;i--)
AdjustDown(i,n-1);
}
/*
template <class T>
void PrioQueue<T>::Print()
{
 for(int i=0;i<n;i++)
 cout<<q[i]>>endl;
}
*/
int main()
{
int x[6]={62,18,30,46,50,70};
int e;
PrioQueue<int> m=PrioQueue<int>(x,6);
try
{
m.Serve(e);
cout<<e;
system("pause");
}
catch(Result err)
{
switch(err)
{   
case Underflow:
cout<<"underflow"<<endl;
break;
case Overflow:
cout<<"overflow"<<endl;   
break;
}
}
}
 
 

 TAG 队列
 发表于: 2008-06-08,修改于: 2008-06-08 10:08 已浏览137次,有评论0条 推荐 投诉

  网友评论

  发表评论



Copyright © 2001-2006 ChinaUnix.net All Rights Reserved

感谢所有关心和支持过ChinaUnix的朋友们
页面生成时间:4.16998

京ICP证041476号