Pikachu
SRM 533 · 2011-11-22 · by cgy4ever
Problem Statement
We need to teach our Pikachu to use N different words, conveniently numbered 0 through N-1. To do this, we need to encode the words into N distinct strings Pikachu will be able to pronounce. For example, we may encode "electric" as "pikapi" and "mouse" as "pikachu". As Pikachu sometimes omits pauses between the words he says, the encoding we will use must be prefix-free. More formally, we need to choose strings code[0], code[1], ..., code[N-1] such that:
- For any i, code[i] must be a string that is generated by concatenating one or more copies of the strings "pi", "ka" and "chu".
- For any distinct i and j, code[i] is not a prefix of code[j].
Let A be the minimal total cost that can be achieved, and let B be the number of distinct codes that have the total cost equal to A. Your method must return a
Constraints
- freq will contain between 2 and 30 elements, inclusive.
- Each element of freq will be between 1 and 1000, inclusive.
{1,1}
Returns: {4, 2 }
We have two words with the same frequency. One of the two optimal codes is ("pi", "ka"), i.e., word 0 is encoded as "pi" and word 1 is encoded as "ka". The total cost of this code is 1*length("pi") + 1*length("ka") = 1*2 + 1*2 = 4. The other optimal code is ("ka", "pi").
{1,1,2}
Returns: {9, 4 }
There are 4 solutions: ("chu", "ka", "pi"), ("ka", "chu", "pi"), ("pi", "chu", "ka") and ("chu", "pi", "ka"). Note that solutions that encode word 2 as "chu" are not optimal.
{1,1,1,1}
Returns: {13, 48 }
One of the 48 optimal codes is ("pi", "chu", "kapi", "kaka").
{2,3,5,7,11,13,17,19}
Returns: {309, 96 }
{533,533,533,353,335,335}
Returns: {10290, 288 }
{1,1,1,1,1,1,1,1,1,1,1,1,1}
Returns: {72, 362124467 }
Don't forget to use modular arithmetics when computing B.
Submissions are judged against all 107 archived test cases, of which 6 are shown here. Case numbers match the judge’s.
Language: C++17 · define a public class Pikachu with a public method vector<int> bestEncoding(vector<int> freq) · 107 test cases · 2 s / 256 MB per case