Fractal Expansion#13044

Fractal Expansion (Editorial)

Solution

Every string that can appear during the process is a prefix of .

Let be the minimum cost needed to obtain the prefix of of length .

Initially,

dp[0]=0.

There are two possible transitions.

Appending one character

Suppose the current prefix has length .

Appending the next character makes its length equal to x+1, and the cost of this operation is x+1.

Therefore,

dp[x+1] = \min(dp[x+1],dp[x]+x+1).

Applying the transformation

Suppose the current string is

s=t_1t_2\dots t_x.

Let

L_x=|f(s)|.

Every character A produces two characters, while every character B produces one character.

Therefore,

L_x=x+\#A(t_1t_2\dots t_x).

After applying the operation, the new string becomes

s+f(s),

so its length becomes

x+L_x.

The operation is valid exactly when

t_{x+1}t_{x+2}\dots t_{x+L_x} = f(t_1t_2\dots t_x).

Now construct

U=f(t).

Since the transformation is applied independently to every character,

f(t_1t_2\dots t_x)

is exactly the prefix of of length L_x.

Thus, we only need to check whether

t_{x+1}t_{x+2}\dots t_{x+L_x} = U_1U_2\dots U_{L_x}.

This is a longest common prefix query between and the suffix of starting from position x+1.

Construct the string

U+\#+t,

where # is a character different from A and B, and calculate its Z-function.

The Z-value corresponding to position x+1 in gives the length of the common prefix between and

t_{x+1}t_{x+2}\dots.

Therefore, the transformation is possible exactly when

x+L_x\le n

and the corresponding Z-value is at least L_x.

Then we can perform the transition

dp[x+L_x] = \min(dp[x+L_x],dp[x]+c).

The answer is .

Correctness

Every reachable string is a prefix of , so it is enough to store only its length.

From a prefix of length , there are exactly two possible operations: append one character or apply the transformation.

The first DP transition handles the append operation.

For the second operation, the Z-function checks exactly whether f(t_1t_2\dots t_x) appears immediately after the current prefix.

Therefore, every valid transition is considered and no invalid transition is added.

Hence, is the minimum possible cost of obtaining the prefix of length , and is the required answer.

Complexity

The string has length at most .

Building , calculating prefix counts, and calculating the Z-function all take time.

Every DP state has at most two transitions.

Therefore, the total complexity is

time and

memory.