C-Hyperhuffman (Haffman value)
C-HyperhuffmanTime Limit:20000/10000 MS (Java/Others)Memory Limit:128000/64000 KB (Java/Others) SubmitStatusProblem Description
You might have heard about Huffman encoding-that is the coding system that minimizes the expected length of the text if the codes for characters are required to consist of an integral number of bits.
Let us recall codes assignment process in Huffman encoding. first the Huffman tree is constructed. let the alphabet consist of N characters, I-th of which occurs Pi times in the input text. initially all characters are considered to be active nodes of the future tree, I-th being marked with Pi. on each step take two active nodes with smallest marks, create the new node, mark it with the sum of the considered nodes and make them the children of the new node. then remove the two nodes that now have parent from the set of active nodes and make the new node active. this process is repeated until only one active node exists, it is made the root of the tree.
Note that the characters of the alphabet are represented by the leaves of the tree. for each leaf node the length of its code in the Huffman encoding is the length of the path from the root to the node. the code itself can be constrcuted the following way: for each internal node consider two edges from it to its children. assign 0 to one of them and 1 to another. the code of the character is then the sequence of 0 s and 1 s passed on the way from the root to the leaf node representing this character.
In this problem you are asked to detect the length of the text after it being encoded with Huffman method. since the length of the code for the character depends only on the number of occurences of this character, the text itself is not given-only the number of occurences of each character. characters are given from most rare to most frequent.
Note that the alphabet used for the text is quite huge-it may contain in up to 500 000 characters.
Input The first line of the input file contains N-the number of different characters used in the text (2 ≤ N ≤500 000 ). the second line contains N integer numbers Pi-the number of occurences of each character (1 ≤ Pi ≤109, Pi ≤ Pi + 1 for all valid I ). output the length of the text after encoding it using Huffman method, in bits. sample Input
31 1 4
Sample Output
8
#include
#include
#include
using namespace std;#define ll long longtypedef struct nnn{ ll sum,v; friend bool operator<(struct nnn a,struct nnn b) { return a.v>b.v; }}node;priority_queue
q;ll count(){ node p1,p2; while(!q.empty()) { p1=q.top(); q.pop(); if(q.empty()) return p1.sum; p2=q.top(); q.pop(); p1.sum+=p2.sum+p1.v+p2.v; p1.v+=p2.v; q.push(p1); }}int main(){ node p; int n; while(scanf("%d",&n)>0) { while(!q.empty())q.pop(); while(n--) { scanf("%lld",&p.v); p.sum=0; q.push(p); } printf("%lld\n",count()); }}