15098 - Memory Encoding   

Description

This problem can be solved with Dynamic Programming, but this practice is about Recursion. Please solve it with Recursion.

Elephants have a very good memory. Elfnt wants to train his own memory, so he decides to compress the words he has to memorize.

An encoded string is written with the following rules:

  • A lowercase letter stands for itself.
  • k[E] stands for the string that E stands for, repeated times. Here is a positive integer written in decimal, and E is any encoded string. For example, 3[ab] stands for ababab.
  • Encoded strings can be written one after another. For example, 2[a]bc stands for aabc.

Since E is again an encoded string, brackets can be nested. For example, 2[2[abbb]c] stands for abbbabbbcabbbabbbc.

The length of an encoded string counts every character in it, including the digits and the brackets. For example, the length of 10[a] is .

If no encoded string is shorter than the word, you can choose not to encode it.

You are given words. For each word, print the length of the shortest encoded string that stands for it.

Hint

For a word s, there are three choices:

  1. Keep s as it is.
  2. If s is some prefix repeated times, write it as k[...] and encode the prefix.
  3. Split s into two parts and encode each part.

Choices 2 and 3 encode shorter words, so they can call the same function again. The same word will be asked for many times, so record every word you have already solved:

memo = {}

def f(x):
    if x in memo:
        return memo[x]
    ...
    memo[x] = ans
    return ans

Input

The first line contains .

Each of the next lines contains one word made of lowercase English letters.

Constraints

  • Each word has length between and .
  • Each word contains only lowercase English letters.

Subtasks

  • Test cases 1–3: Each word has length at most .
  • Test cases 4–10: No additional constraints.

Output

Print lines. The -th line contains one integer: the length of the shortest encoded string for the -th word.

End every line with a newline, including the last.

Sample Input  Download

Sample Output  Download

Explanation

  • aaa: 3[a] has length , which is longer than the word itself, so the answer is .
  • aaaaa: 5[a] has length .
  • ababababcdabcd: 4[ab]cdabcd has length .
  • elephant: nothing can be made shorter.
  • abbbabbbcabbbabbbc: 2[2[abbb]c] has length .

Sample Input  Download

Sample Output  Download




Discuss