Correcting Curiosity
Time limit2sMemory limit256 MB
Given two strings, find the length of the shortest substitution command that rewrites the first into the second.
- Level
Hard8 of 10
- Topics
- String matching, String, Dynamic programming
- Solved
- No attempts yet
Problem
Curiosity is the rover that explores Gale Crater on Mars. It recently found evidence of water in Martian soil, which makes planning the future manned missions easier.
Curiosity communicates with Earth directly at speeds up to 32 Kbit/s, but a signal needs 14 minutes and 6 seconds on average to travel between Earth and Mars.
Matt Heverly, the rover's driver, explains it this way. "You have just seen a stone and applied brakes, but you know that the rover is already passing that stone. So we just plan the route, then write down a list of simple textual commands: move one meter ahead, turn left, make a photo and so on."
Sometimes you have to react to an unexpected event very fast. If the cameras have seen something interesting, you may want to change the route of the rover and take one more photo. To do that you send a substitution command of the form s/⟨string⟩/⟨replacement⟩/g. It walks from the leftmost occurrence of ⟨string⟩ and replaces every occurrence with ⟨replacement⟩.
More formally, if is a non-empty string and is a string, applying the substitution command s/A/B/g to a string works like this.
- Find the leftmost occurrence of in , so that .
- If there is no such occurrence, stop. Then is the answer.
- Let be the result of applying
s/A/B/gto . - The answer is .
Two things follow.
- If two occurrences of in overlap, only the leftmost one is replaced. Applying
s/aba/c/gtoabababayieldscbc: replacing the firstabaturns the string intocbaba, and after that only the lastabacan be replaced. - No substitution uses the result of a previous substitution. Applying
s/a/ab/gtoayieldsab, and applyings/a/ba/gtoayieldsba.
The longer the command, the more time it takes to transmit. Find the shortest substitution command that turns the initial string into the final string.
Input
The first line contains the initial string and the second line contains the final string. Both strings are non-empty and their lengths do not exceed 2000 characters. The strings contain only English letters, spaces and punctuation signs (commas, colons, semicolons and hyphens: , : ; -). The two given strings are different.
Output
Print one integer, the length of the shortest substitution command that transforms the initial string into the final string.
The command s/A/B/g is characters long. Such a command always exists.