Pagini recente » Cod sursa (job #1165271) | Cod sursa (job #1247405) | Cod sursa (job #1470683) | Cod sursa (job #1079030) | Cod sursa (job #1707376)
#include <fstream>
using namespace std;
template<class Type>
class PriorityQueue
{
private:
int LeftSon(int poz);
int RightSon(int poz);
int Father(int poz);
void Upheap(int poz);
void Downheap(int poz);
int nh, alocate_current;
Type *H;
public:
PriorityQueue();
PriorityQueue(const PriorityQueue &cpy);
~PriorityQueue();
void push(Type x);
Type pop();
Type front();
};
template<typename Type>
int PriorityQueue<Type> :: LeftSon(int poz)
{
return 2*poz;
}
template <class Type>
int PriorityQueue<Type> :: RightSon(int poz)
{
return 2*poz+1;
}
template <class Type>
int PriorityQueue<Type> :: Father(int poz)
{
return poz/2;
}
template <class Type>
void PriorityQueue<Type> :: Upheap(int poz)
{
while(true)
{
if(poz==1)
return;
if(H[Father(poz)]< H[poz])
{
swap(H[poz],H[Father(poz)]);
poz=Father(poz);
}
else
return;
}
}
template< class Type>
void PriorityQueue<Type> :: Downheap(int poz)
{
while(true)
{
if(poz>nh)
return;
if(LeftSon(poz)<=nh)
{
int poz_max;
if(RightSon(poz)<=nh)
{
if(H[RightSon(poz)] < H[LeftSon(poz)])
poz_max=LeftSon(poz);
else
poz_max=RightSon(poz);
}
else
poz_max=LeftSon(poz);
if(H[poz] < H[poz_max])
{
swap(H[poz], H[poz_max]);
poz=poz_max;
}
else
return ;
}
else
return;
}
}
template<class Type>
PriorityQueue<Type> :: PriorityQueue()
{
nh=0;
alocate_current=10;
H=new Type[alocate_current];
}
template <class Type>
PriorityQueue<Type> :: PriorityQueue(const PriorityQueue &cpy)
{
this->nh=cpy.nh;
this->alocate_current=cpy.alocate_current;
this->H= new Type[alocate_current];
for(int i=1; i<=cpy.nh; i++)
this->H[i]=cpy.H[i];
}
template<class Type>
PriorityQueue<Type> :: ~PriorityQueue()
{
delete[] H;
nh=0;
alocate_current=0;
}
template <class Type>
void PriorityQueue<Type> :: push(Type x)
{
nh++;
if(nh==alocate_current)
{
alocate_current*=2;
Type *aux;
aux= new Type[alocate_current];
for(int i=1; i<nh; i++) ///am facut sus nh++..de aia aici e <nh nu <=
{
aux[i]=H[i];
}
delete[] H;
H=aux;
}
H[nh]=x;
Upheap(nh);
}
template <class Type>
Type PriorityQueue<Type> :: pop()
{
Type rez=H[1];
H[1]=H[nh];
nh--;
Downheap(1);
if(nh<alocate_current/2 && alocate_current!= 10)
{
alocate_current=alocate_current/2;
Type *aux;
aux= new Type[alocate_current];
for(int i=1; i<=nh; i++)
{
aux[i]=H[i];
}
delete[] H;
H=aux;
}
return rez;
}
template <class Type>
Type PriorityQueue<Type> :: front()
{
return H[1];
}
int v[500010];
int main()
{
PriorityQueue <int> Q;
ifstream f("algsort.in");
int n;
f >> n;
for(int i =1; i<=n; i++)
{
int x;
f>>x;
Q.push(x);
}
for(int i=1; i <=n; i++)
v[i] = Q.pop();
ofstream g("algsort.out");
for(int i=n; i >=1; i--)
g << v[i] <<" ";
g<<"\n";
g.close();
return 0;
}