Pagini recente » Cod sursa (job #2594295) | Cod sursa (job #482482) | Cod sursa (job #3287222) | Cod sursa (job #2467998) | Cod sursa (job #479732)
Cod sursa(job #479732)
#include <fstream>
#include <vector>
#include <deque>
#include <queue>
using namespace std;
#define code count
struct node
{
int left, right;
long long count;
short len;
node()
{
left = right = -1;
}
};
int n;
vector<node> c;
int st, dr;
void bfs()
{
int n;
queue<int> q;
q.push(c.size() - 1);
c[c.size() - 1].code = 0;
c[c.size() - 1].len = 0;
while(!q.empty())
{
n = q.front(); q.pop();
if(c[n].left == -1)
continue;
else
{
long long code = c[n].code << 1;
int l = c[n].left, r = c[n].right;
c[l].code = code;
c[r].code = code + 1;
c[l].len = c[r].len = c[n].len + 1;
q.push(l);
q.push(r);
}
}
}
inline int pop()
{
if(st==n)
return dr ++;
if(dr==c.size())
return st ++;
if(c[st].count <= c[dr].count)
return st ++;
return dr++;
}
char buf[1000000];
int main()
{
ifstream cin("huffman.in");
cin.rdbuf()->pubsetbuf(buf, sizeof(buf));
ofstream cout("huffman.out");
c.reserve(2000000);
int x;
cin >> n;
c.resize(n);
for(int i=0;i<n;++i)
{
cin >> x;
c[i].right = c[i].left = -1;
c[i].count = x;
}
st = 0; dr = n;
long long count = 0;
int s, d;
while((n-st+c.size()-dr) > 1)
{
s = pop();
d = pop();
c.push_back(node());
node &n = c[c.size() - 1];
n.count = c[s].count + c[d].count;
count += n.count;
n.left = s;
n.right = d;
}
bfs();
cout << count << endl;
for(int i=0;i<n;++i)
cout << c[i].len << " " << c[i].code << "\n";
return 0;
}