Codeforces Round 364 (Div. 1)
D
Huffman Coding on Segment
Codeforces
3100
原题
← CE →
翻译中…

Alice wants to send an important message to Bob. Message $*a* = (*a*_{1}, ..., *a*_{*n*})$ is a sequence of positive integers (characters).

翻译中…

To compress the message Alice wants to use binary Huffman coding. We recall that binary Huffman code, or binary prefix code is a function $*f*$, that maps each letter that appears in the string to some binary string (that is, string consisting of characters '0' and '1' only) such that for each pair of different characters $*a*_{*i*}$ and $*a*_{*j*}$ string $*f*(*a*_{*i*})$ is not a prefix of $*f*(*a*_{*j*})$ (and vice versa). The result of the encoding of the message $*a*_{1}, *a*_{2}, ..., *a*_{*n*}$ is the concatenation of the encoding of each character, that is the string $*f*(*a*_{1})*f*(*a*_{2})... *f*(*a*_{*n*})$. Huffman codes are very useful, as the compressed message can be easily and uniquely decompressed, if the function $*f*$ is given. Code is usually chosen in order to minimize the total length of the compressed message, i.e. the length of the string $*f*(*a*_{1})*f*(*a*_{2})... *f*(*a*_{*n*})$.

翻译中…

Because of security issues Alice doesn't want to send the whole message. Instead, she picks some substrings of the message and wants to send them separately. For each of the given substrings $*a*_{*l*_{*i*}}... *a*_{*r*_{*i*}}$ she wants to know the minimum possible length of the Huffman coding. Help her solve this problem.

翻译中…

Input

翻译中…

The first line of the input contains the single integer $*n*$ ($1 ≤ *n* ≤ 100 000$) — the length of the initial message. The second line contains $*n*$ integers $*a*_{1}, *a*_{2}, ..., *a*_{*n*}$ ($1 ≤ *a*_{*i*} ≤ 100 000$) — characters of the message.

翻译中…

Next line contains the single integer $*q*$ ($1 ≤ *q* ≤ 100 000$) — the number of queries.

翻译中…

Then follow $*q*$ lines with queries descriptions. The $*i*$-th of these lines contains two integers $*l*_{*i*}$ and $*r*_{*i*}$ ($1 ≤ *l*_{*i*} ≤ *r*_{*i*} ≤ *n*$) — the position of the left and right ends of the $*i*$-th substring respectively. Positions are numbered from $1$. Substrings may overlap in any way. The same substring may appear in the input more than once.

翻译中…

Output

翻译中…

Print $*q*$ lines. Each line should contain a single integer — the minimum possible length of the Huffman encoding of the substring $*a*_{*l*_{*i*}}... *a*_{*r*_{*i*}}$.

翻译中…

Note

翻译中…

In the first query, one of the optimal ways to encode the substring is to map $1$ to "0", $2$ to "10" and $3$ to "11".

翻译中…

Note that it is correct to map the letter to the empty substring (as in the fifth query from the sample).

翻译中…

样例

Input #1
7
1 2 1 3 1 2 1
5
1 7
1 3
3 5
2 4
4 4
Output #1
10
3
3
5
0
InputCopy OutputCopy
题目信息
题号
700D
时间限制
4 s
内存限制
256 MB
标签
数据结构
贪心

题面与样例版权归 Codeforces 及出题人所有;中文翻译由 AI 生成(CI 管线),如有出入请以原文为准。