| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 559 人关注过本帖
标题:写了个关于优先权队列的程序
只看楼主 加入收藏
lijianbo
Rank: 1
等 级:新手上路
帖 子:9
专家分:0
注 册:2006-3-25
收藏
 问题点数:0 回复次数:0 
写了个关于优先权队列的程序

#include<iostream.h>
enum ResultCode{Overflow,Underflow};

template<class T>
class PrioQueue
{
public:
PrioQueue(int mSize);
~PrioQueue(){delete []q;};
void Append(const T &x);
void Serve(T &x);
bool IsEmpty() const{return n==0;}
bool IsFull() const{return n==maxSize;}

void Output(ostream& out)const;
void AdjustDown(int r,int j);
void AdjustUp(int j);

private:
T *q;
int n,maxSize;
friend ostream &operator<<(ostream & out,const PrioQueue<T>& s);
};
template<class T>
PrioQueue<T>::PrioQueue(int mSize)
{
maxSize=mSize;
n=0;
q=new T[maxSize];
}
template<class T>
void PrioQueue<T>::AdjustUp(int j)
{
int i=j;T temp=q[i];
while(i>0&&temp<q[(i-1)/2])
{
q[i]=q[(i-1)/2];i=(i-1)/2;
}
q[i]=temp;
}
template<class T>
void PrioQueue<T>::AdjustDown(int r,int j)
{
int i=2*r+1;
T temp=q[r];
while(i<=j)
{
if((i<j)&&(q[i]>q[i+1])) i++;
if(temp<=q[i])break;
q[(i-1)/2]=q[i];
i=2*i+1;
}
q[(i-1)/2]=temp;
}



template<class T>
void PrioQueue<T>::Append(const T &x)
{
if(IsFull())throw Overflow;
q[n++]=x;
AdjustUp(n-1);
}
template<class T>
void PrioQueue<T>::Serve(T &x)
{
if(IsEmpty())throw Underflow;
x=q[0];q[0]=q[--n];
AdjustDown(0,n-1);

}
template<class T>
void PrioQueue<T>::Output(ostream& out)const
{
out<<endl<<"The PrioQueue contains:";
for(int i=0;i<n;i++)
out<<q[i]<<" ";

}
template<class T>
ostream &operator<<(ostream& out,const PrioQueue<T>& s)
{
s.Output(out);
return out;
}
void main()
{
try{
PrioQueue<int>a(10);
a.Append(71);
a.Append(74);
a.Append(2);
a.Append(72);
a.Append(54);
a.Append(93);
a.Append(52);
a.Append(28);
int x,y;
a.Serve(x);
cout<<a<<endl;

a.Serve(y);

cout<<a<<endl;





}
catch(ResultCode err)
{
switch(err)
{
case Overflow:cout<<"Overflow!"<<endl;break;
case Underflow:cout<<"Underflow!"<<endl;break;
}
}
}

搜索更多相关主题的帖子: 优先权 队列 
2006-04-30 20:18
快速回复:写了个关于优先权队列的程序
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014274 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved