Cod sursa(job #848602)

Utilizator enedumitruene dumitru enedumitru Data 5 ianuarie 2013 17:18:36
Problema Coduri Huffman Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.99 kb
#include<fstream>
#include<queue>
#define LL long long
using namespace std;
const int Nmax = 1000001;
ifstream in("huffman.in"); ofstream out("huffman.out");
struct cuplu {LL cost; int poz;};
LL lg, bz[Nmax], vall[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(vall[nr]==0) vall[nr] = t.cost;
    if(q1.empty() && q2.empty()) return;
    q2.push(t);
}
void df(int nod, int niv, LL b10)
{   if(nod!=nr) lg += vall[nod];
    if(nod<=n)
        { nrbiti[nod] = niv;  bz[nod] = b10; return;}
    df(fd[nod], niv+1, 2*b10 + 1);
    df(fs[nod], niv+1, 2*b10);
}
int main()
{   int i, a;
    cuplu t,t1,t2;
    in >> n;
    for(i=1; i<=n; ++i)
        {   in >> a;  vall[i]=a;
            t.poz = i; t.cost = a; 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);
    out << lg << "\n";
    for(i=1;i<=n;++i)
        out << nrbiti[i] << " " << bz[i] << "\n";
    out.close(); return 0;
}