Fork
Time limit0.15sMemory limit1024 MB
Given P, N, L, and R, find the minimum expected number of key presses to finish typing a fixed N-character string into two random shells.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Probability
- Solved
- No attempts yet
Problem
Luca opened a Python shell and typed os.fork(), which spawned a second shell. After that, each time Luca pressed any key, it would randomly go to one of the two shells. Each shell has an input string (shown in the terminal), which is edited by the key presses going to that shell. Luca also sees the terminal, so he knows which shell's input string was affected when he presses a key.
His keyboard has keys with distinct characters on them and Backspace. When a character key press goes to a shell, the character is appended to the end of its input string. When a Backspace key press goes to a shell, the last character of its input string is erased. If the shell's input string is empty, nothing happens to it, though Luca still sees that the Backspace went there. Each key press has probability of going to the left shell and probability of going to the right one.
Luca wants to type a fixed string of distinct characters into both shells. He has already typed correct characters into the left shell and into the right one, so the strings in the two shells are and .
For example, consider , (the string could be ab), and . A possible sequence of events is:
In this case, typing ab into both shells took 12 key presses.
An incorrect character is a character in one of the two shells that must be deleted at some point before the full string is typed into both shells. Only such characters count as incorrect.
Luca has decided that he will never press Backspace unless at least one of the shells contains an incorrect character. He has also decided that he will never press a key that always produces an incorrect character. Luca wants the strategy with the minimum expected number of key presses.
Write a program fork.cpp that solves this problem.
Input
The first and only line of standard input contains , , , and .
Output
Print the answer on the first and only line of standard output. Print it with at least 12 digits of precision. You can use:
std::cout << std::setprecision(12) << ans << std::endl;
Constraints