Pagini recente » Cod sursa (job #1887764) | Cod sursa (job #2016984) | Cod sursa (job #2149232) | Atasamentele paginii Poze preONI 2007 - deschidere | Cod sursa (job #1999078)
#include <iostream>
#include <cstdio>
#include <queue>
#define NMAX 1000005
using namespace std;
int n, nrTati=1, sol;
pair <int, int> tati[NMAX];
queue <pair <long, int> >q1, q2;
void read()
{
scanf("%d", &n);
int x;
for(int i=1; i<=n; ++i)
{
scanf("%d", &x);
q1.push(make_pair(x, i));
}
}
int minim()
{
int x;
if(!q1.empty() && q1.front().first <= q2.front().first)
{
x=q1.front().first;
q1.pop();
}
else if(!q2.empty())
{
x=q2.front().first;
q2.pop();
}
return x;
}
void codare()
{
int x1 = q1.front().first;
q1.pop();
int x2 = q1.front().first;
q1.pop();
q2.push(make_pair(x1+x2, ++n));
sol += x1+x2;
tati[nrTati].first = n;
tati[nrTati].second = 0;
nrTati++;
tati[nrTati].first = n;
tati[nrTati].second = 1;
nrTati++;
while(q1.size() + q2.size() > 1)
{
x1 = minim();
if(q1.size() + q2.size() >= 1)
x2 = minim();
q2.push(make_pair(x1 + x2, ++n));
sol += x1+x2;
x1 = 0;
x2 = 0;
tati[nrTati].first = n;
tati[nrTati].second = 0;
nrTati++;
tati[nrTati].first = n;
tati[nrTati].second = 1;
nrTati++;
}
if(!q1.empty())
{
sol+=q1.front().first;
}
}
int main()
{
freopen("huffman.in", "r", stdin);
freopen("huffman.out", "w", stdout);
read();
codare();
printf("%d", sol);
return 0;
}