<|instruction|>
Solve the below problem. The solution should start with an abridged problem statement. Then key observations. Then full solution based on the observations. Then C++ and Python implementations with comments.

203. Hyperhuffman
time limit per test: 0.25 sec.
memory limit per test: 65536 KB
input: standard
output: standard



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 0s and 1s 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 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
Output the length of the text after encoding it using Huffman method, in bits.

Sample test(s)

Input
3
1 1 4

Output
8
Author:	Andrew Stankevich
Resource:	Petrozavodsk Summer Trainings 2003
Date:	2003-08-23

<|response|>
1. Abridged problem statement  
Given N sorted character frequencies P₁ ≤ P₂ ≤ … ≤ Pₙ, build a Huffman tree by repeatedly merging the two smallest active weights a and b into (a+b), adding (a+b) to the total cost, and reinserting (a+b). Continue until one weight remains. Output the total cost (the total number of bits in the encoded text).

2. Key observations needed to solve the problem  
- Huffman’s algorithm always picks the two smallest weights to merge; the sum of all merges equals the total encoded length.  
- A priority queue (min‐heap) yields O(N log N) time, which is acceptable in C++ for N up to 500 000.  
- Since the input frequencies are already sorted, one can achieve O(N) time by using two FIFO queues:  
  • q1 holds the original sorted frequencies.  
  • q2 holds the merged sums, which are produced in non‐decreasing order.  
- At each step, the two smallest available weights are simply the smaller fronts of q1 and q2.

3. Full solution approach based on the observations  
a. Read N and the sorted list of frequencies into q1.  
b. Initialize an empty queue q2 and a variable totalCost = 0.  
c. While (size of q1 + size of q2) > 1:  
   i.  Pop the smaller of q1.front() and q2.front() → first.  
   ii. Pop again the smaller of q1.front() and q2.front() → second.  
   iii. Let combined = first + second.  
   iv. totalCost += combined.  
   v.  Push combined into q2.  
d. When one weight remains, totalCost is the answer.  
e. Print totalCost.

4. C++ implementation with detailed comments  
```cpp
#include <iostream>
#include <queue>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);

    int n;
    // Read the number of distinct characters
    cin >> n;

    // q1: holds original sorted frequencies
    // q2: holds merged sums, also non-decreasing
    queue<long long> q1, q2;

    // Read all frequencies into q1
    for (int i = 0; i < n; i++) {
        long long freq;
        cin >> freq;
        q1.push(freq);
    }

    long long totalCost = 0;  // Accumulate sum of all merges

    // Continue until only one weight remains across both queues
    while ((int)(q1.size() + q2.size()) > 1) {
        long long first, second;

        // Extract the smaller of the two queue fronts twice
        for (int k = 0; k < 2; k++) {
            bool takeFromQ1;
            // If q2 is empty, or q1.front() < q2.front(), take from q1
            if (q2.empty() || (!q1.empty() && q1.front() < q2.front())) {
                takeFromQ1 = true;
            } else {
                takeFromQ1 = false;
            }

            if (takeFromQ1) {
                if (k == 0) first = q1.front();
                else         second = q1.front();
                q1.pop();
            } else {
                if (k == 0) first = q2.front();
                else         second = q2.front();
                q2.pop();
            }
        }

        // Merge the two smallest weights
        long long combined = first + second;
        totalCost += combined;  // This merge contributes combined bits
        // Insert the new weight into q2
        q2.push(combined);
    }

    // Output the total bit-length of the Huffman-encoded text
    cout << totalCost << "\n";
    return 0;
}
```

5. Python implementation with detailed comments  
```python
import sys
from collections import deque

def main():
    data = sys.stdin.read().split()
    # First value is N, then N sorted frequencies
    n = int(data[0])
    freqs = list(map(int, data[1:]))

    # q1: initial frequencies; q2: merged sums
    q1 = deque(freqs)
    q2 = deque()

    total_cost = 0

    # Helper to pop the smallest front element from q1 or q2
    def pop_min():
        # If q2 is empty or q1 has the smaller front, pop from q1
        if not q2 or (q1 and q1[0] < q2[0]):
            return q1.popleft()
        else:
            return q2.popleft()

    # Continue merging until one weight remains
    while len(q1) + len(q2) > 1:
        first = pop_min()
        second = pop_min()
        combined = first + second
        total_cost += combined
        # Push the merged sum into q2
        q2.append(combined)

    # Print the total bit-length
    print(total_cost)

if __name__ == "__main__":
    main()
```