Cod sursa(job #848630)

Utilizator enedumitruene dumitru enedumitru Data 5 ianuarie 2013 17:35:43
Problema Coduri Huffman Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2 kb
#include<fstream>
#include<queue>
#define LL long long
using namespace std;
const int Nmax = 1000001;
ifstream f("huffman.in"); ofstream g("huffman.out");
struct cuplu {LL cost; int poz;};
LL lg, bz[Nmax], val[2*Nmax];
int n, nr, fs[2*Nmax], fd[2*Nmax], nrbiti[Nmax];
queue <cuplu> q1, q2;
inline void cr(const cuplu &a, const cuplu &b)
{   cuplu t;
    t.cost = a.cost + b.cost; t.poz = ++nr;
    fd[nr] = a.poz; fs[nr] = b.poz;
    if(val[nr]==0) val[nr] = t.cost;
    if(q1.empty() && q2.empty()) return;
    q2.push(t);
}
inline void df(int nod, int niv, LL b10)
{   if(nod!=nr) lg += val[nod];
    if(nod<=n)
        { nrbiti[nod] = niv;  bz[nod] = b10; return;}
    LL nrfs=(b10<<1);  LL nrfd=nrfs+1;
    df(fd[nod], niv+1, nrfd);
    df(fs[nod], niv+1, nrfs);
}
int main()
{   cuplu t,t1,t2;
    f >> n;
    for(int i=1; i<=n; ++i)
        {   f >>val[i];
            t.poz = i; t.cost = val[i]; q1.push(t);
        }
    nr = n;
    while(!q1.empty() || !q2.empty())
    {   if(q1.empty())
            { t1=q2.front(); q2.pop();
          	  t2=q2.front(); q2.pop();
          	  cr(t1,t2);
          	  continue;
        	}
        if(q2.empty())
            { t1=q1.front(); q1.pop();
              t2=q1.front(); q1.pop();
              cr(t1,t2);
              continue;
        	}
        if(q1.front().cost > q2.front().cost)
             { t1 = q2.front(); q2.pop();}
        else { t1 = q1.front(); q1.pop();}
        if(q1.empty())
            { t2 = q2.front(); q2.pop();
              cr(t1,t2);
              continue;
            }
        if(q2.empty())
            { t2 = q1.front(); q1.pop();
              cr(t1,t2);
              continue;
             }
        if(q1.front().cost > q2.front().cost)
             { t2 = q2.front(); q2.pop();}
        else { t2 = q1.front(); q1.pop();}
        cr(t1,t2);
    }
    df(nr,0,0);
    g << lg << "\n";
    for(int i=1; i<=n; ++i)
        g << nrbiti[i] << " " << bz[i] << "\n";
    g.close(); return 0;
}