Pagini recente » Cod sursa (job #1935892) | Cod sursa (job #2483402) | Cod sursa (job #499594) | Cod sursa (job #968473) | Cod sursa (job #1322415)
//Deresu Roberto - FMI
//Re :)
#include<fstream>
#include<queue>
#define nx 2000007
using namespace std;
int n, m, v[nx];
long long sum;
queue<pair<int, int> >q1, q2;
struct st
{
int value;
int left;
int right;
}a[nx];
struct str
{
int len;
int cod;
}b[nx/2];
ifstream fin("huffman.in");
ofstream fout("huffman.out");
void Minim(int &nr, int &pos)
{
pair<int, int> a;
if(q1.empty())
{
a = q2.front();
q2.pop();
}
else
if(q2.empty())
{
a = q1.front();
q1.pop();
}
else
if(q1.front().first < q2.front().first)
{
a = q1.front();
q1.pop();
}
else
{
a = q2.front();
q2.pop();
}
nr = a.first;
pos = a.second;
}
void Dfs(int pos, int cod, int len)
{
if(a[pos].left)
Dfs(a[pos].left, cod<<1, len+1);
if(a[pos].right)
Dfs(a[pos].right, (cod<<1)+1, len+1);
if(a[pos].left == 0 && a[pos].right == 0)
{
n++;
b[pos].cod = cod;
b[pos].len = len;
}
else sum += a[pos].value;
}
int cmp(str a, str b)
{
if(a.len >= b.len) return 1;
return 0;
}
int main()
{
fin>>n;
for(int i = 1; i <= n; i++)
{
fin >> a[i].value;
q1.push(make_pair(a[i].value, i));
}
while(q1.size()+q2.size() != 1)
{
int nr1, pos1, nr2, pos2;
Minim(nr1, pos1);
Minim(nr2, pos2);
n++;
a[n].value = nr1+nr2;
q2.push(make_pair(a[n].value, n));
a[n].left = pos1;
a[n].right = pos2;
}
n = 0;
Dfs(q2.front().second, 0, 0);
fout << sum << '\n';
for(int i = 1; i <= n; i++)
fout << b[i].len << " " << b[i].cod << '\n';
return 0;
}