Cod sursa(job #2557714)

Utilizator Briana_NeaguNeagu Briana Briana_Neagu Data 25 februarie 2020 22:43:56
Problema Coduri Huffman Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("huffman.in");
ofstream g("huffman.out");

const int nmax = 1e6 + 5;


struct cmp
{
    bool operator() (const pair <long long, int> a, const pair <long long, int> b)
    {
        return a.first > b.first;
    }
};

priority_queue <pair <long long, int>, vector <pair <long long, int> >, cmp>  Q;
pair <long long, pair <int, int> > nodes[nmax * 2];
pair <int, long long> ans[nmax];

long long  dfs(int curNode, int depth, long long code)
{
   // cout << "code : "  << code << '\n';
    if (nodes[curNode].second.first == -1) // e frunza
    {
        ans[curNode].first = depth;
        ans[curNode].second = code;
        return depth * nodes[curNode].first;
    }
    long long ans = 0;
    ans += dfs(nodes[curNode].second.first, depth + 1, (code << 1LL));
    ans += dfs(nodes[curNode].second.second, depth + 1, (code << 1LL) + 1);
    return ans;
}

int main()
{
   int n;
   f >> n;
   for (int i = 1; i <= n; ++ i)
   {
       int fv;
       f >> fv;
       nodes[i] = {fv, {-1, -1}};
       Q.push({fv, i});
   }
   int howMany = n;
   while (Q.size() > 1)
   {
       auto left = Q.top();
       Q.pop();
       auto right = Q.top();
       Q.pop();
       nodes[++ howMany] = {left.first + right.first, {left.second, right.second}};
       Q.push({nodes[howMany].first, howMany});
   }
   g << dfs(howMany, 0, 0) << '\n';
   for (int i = 1; i <= n; ++ i)
       g << ans[i].first << " " << ans[i].second << '\n';
}