Pagini recente » Arhiva de probleme | Cod sursa (job #337047) | Cod sursa (job #1777875) | Cod sursa (job #1639678) | Cod sursa (job #1741009)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <math.h>
#define MAX_HEAP_SIZE 1000001
using namespace std;
ifstream in;
ofstream out;
unsigned long long int heap [MAX_HEAP_SIZE], n, Q[500000], pos[MAX_HEAP_SIZE], LU[MAX_HEAP_SIZE], ST[MAX_HEAP_SIZE], DR[MAX_HEAP_SIZE], nr, c=1, T, viz[MAX_HEAP_SIZE], NUMAR_AIUREA;
char cod [64];int contor;
int defeu (int k)
{
NUMAR_AIUREA=0;
viz[k]=1;
if(ST[k] && DR[k])
{
if(!viz[ST[k]])
{
cod[contor]=1;
++contor;
defeu(ST[k]);
}
if(!viz[DR[k]])
{
cod[contor]=0;
++contor;
defeu(DR[k]);
}
}
else
{
out<<contor<<" ";
for(int j=0;j<contor;++j)
{
NUMAR_AIUREA+=pow(2, contor-1-j) * cod[j];
}
out<<NUMAR_AIUREA<<"\n";
}
--contor;
}
void sift(unsigned long long int * h,unsigned long long int i) ///down
{
int k, j=0;
k=i;
while(j!=k)
{
j=k;
if((2*j<=nr ) && (h[2*j] < h[k]))
k=2*j;
if((2*j<nr) && (h[2*j+1]< h[k]))
k=2*j+1;
swap(h[j], h[k]);
swap(pos[j], pos[k]);
}
}
void percolate(unsigned long long int * h, unsigned long long int i) ///up
{
int k, j=0;
k=i;
while(j!=k)
{
j=k;
if((j>1) && (h[j/2]>h[k]))
k=j/2;
swap(h[j], h[k]);
swap(pos[j], pos[k]);
}
}
unsigned long long int find_min(unsigned long long int *h)
{
return h[1];
}
void delete_max(unsigned long long int * h)
{
h[1]=h[nr];
pos[1]=pos[nr];
//--nr
sift(h, 1);
}
void insert_heap(unsigned long long int * h, unsigned long long int val)
{
h[nr]=val;
//pos[nr]=nr;
pos[nr]=c;
++c;
percolate(h, nr);
}
///PANA AICI AU FOST PORCARIILE ALEA DE LA HEAP
int main()
{
in.open ("huffman.in");
out.open ("huffman.out");
in>>n;
for(int i = 1;i<=n;++i)
{
in>>Q[i]; ///lungimile sirurilor
++nr;
insert_heap(heap, Q[i]);
LU[i]=Q[i];
ST[i]=0;
DR[i]=0;
}
///amu algoritmu propriu-zis
int s, j, r, k;
/*cout<<"Heapul cu "<<nr<<" elem: ";
for(int j=1;j<=nr;++j)
cout<<heap[j]<<" ";
cout<<endl;
for(int j=1;j<=n;++j)
cout<<pos[j]<<" ";
cout<<"\n\n";*/
for(int i=n+1;i<2*n;++i)
{
///luam doua cele mai scurte siruri
s=find_min(heap);
j=pos[1];
delete_max(heap);
--nr;
r=find_min(heap);
k=pos[1];
delete_max(heap);
--nr;
ST[i]=j;
DR[i]=k;
LU[i]=s+r;
++nr;
insert_heap(heap, LU[i]);
}
for(int i=n+1;i<2*n;++i)
T+=LU[i];
// for(int i =1;i<2*n;++i)
// cout<<ST[i]<<" "<<LU[i]<<" "<<DR[i]<<"\n";
out<<T<<"\n";
defeu(2*n-1);
in.close();
out.close();
return 0;
}