Pagini recente » Cod sursa (job #3201536) | Cod sursa (job #178470) | Cod sursa (job #2218921) | Cod sursa (job #2812967) | Cod sursa (job #2849692)
#include <fstream>
#include <queue>
using std::queue;
typedef long long ll;
const int NMAX = 1000000;
struct nodes{
int st;
int dr;
};
struct codes{
int depth;
ll code;
};
std::ifstream fin("huffman.in");
std::ofstream fout("huffman.out");
nodes next[2 + 2 * NMAX];
codes ans[2 + 2 * NMAX];
queue<int> Q_init, Q;
ll v[2 + 2 * NMAX];
ll r;
int getMinim()
{
int ans;
if(Q_init.empty())
{
ans = Q.front();
Q.pop();
return ans;
}
if(Q.empty())
{
ans = Q_init.front();
Q_init.pop();
return ans;
}
if(v[Q.front()] <= v[Q_init.front()])
{
ans = Q.front();
Q.pop();
}
else
{
ans = Q_init.front();
Q_init.pop();
}
return ans;
}
void createNode(int u, int y, int nou)
{
v[nou] = v[u] + v[y];
Q.push(nou);
r = r + v[nou];
next[nou].st = u;
next[nou].dr = y;
}
void huffman(int root)
{
if(next[root].st == -1)
return;
ans[next[root].st].depth = ans[root].depth + 1;
ans[next[root].dr].depth = ans[root].depth + 1;
ans[next[root].st].code = (1LL * ans[root].code * 2);
ans[next[root].dr].code = (1LL * ans[root].code * 2) + 1;
huffman(next[root].st);
huffman(next[root].dr);
}
int main()
{
int n,i,x,y,aux;
fin >> n;
aux = n;
for(i = 1; i <= n; i++)
{
fin >> v[i];
next[i].st = next[i].dr = -1;
Q_init.push(i);
}
while(Q_init.size() + Q.size() > 1)
{
x = getMinim();
y = getMinim();
createNode(x, y, ++n);
}
fout << r << "\n";
huffman(n);
for(i = 1; i <= aux; i++)
fout << ans[i].depth << " " << ans[i].code << "\n";
return 0;
}