#P1132. Minimal Steps in the Digit Generation Game

    ID: 13396 Type: Default 1000ms 256MiB

Minimal Steps in the Digit Generation Game

Minimal Steps in the Digit Generation Game

Given a starting number s (which does not contain the digit 0) and a target number t, you need to determine the minimum number of operations required to transform s into t using the following three rules. In each operation, you can generate a new number from the current number according to one of the rules below:

  1. Swap: Swap any two digits of the current number. For example, from 143 you can obtain 413, 341, or 134.
  2. Deletion: Remove any one digit from the current number. For example, from 143 you can obtain 43, 13, or 14.
  3. Insertion: Add one digit between any two adjacent digits of the current number. Suppose the two adjacent digits are \(s_i\) and \(s_{i+1}\); you can insert a digit \(x\) provided that \(s_i < x < s_{i+1}\) (in \(\LaTeX\) this is \( s_i < x < s_{i+1} \)). For example, from 143 you can insert a digit between \(1\) and \(4\) to obtain 1243 or 1343 (since \(1 < 2 < 4\) and \(1 < 3 < 4\)).

Important Constraint on Rule 3: The number of digits in any number generated by insertion cannot exceed the number of digits in the initial number s. For instance, if s is 143, then numbers like 1243 or 1343 cannot be generated directly. However, if s is 1443, you can first apply the deletion rule (generating 143) and then apply the insertion rule.

Your task is to compute the minimum number of operations needed to transform s into t by applying these rules sequentially. If it is impossible to reach t from s using any sequence of valid operations, output -1.

inputFormat

The input consists of a single line with two space-separated numbers s and t. The number s does not contain the digit 0.

For example:

143 134

outputFormat

Output a single integer representing the minimum number of operations required to transform s into t. If it is impossible, output -1.

sample

143 134
1