I am tying to solve this problem:
The cows of Farmer Brown and Farmer John are planning a coordinated escape from their respective farms and have devised a method of encryption to protect their written communications.
Specifically, if one cow has a message, say, "International Olympiad in Informatics", it is altered by inserting the letters C, O, and W, in random location in the message, such that C appears before O, which appears before W. Then the cows take the part of the message between C and O, and the part between O and W, and swap them. Here are two examples:
International Olympiad in Informatics
->
CnOIWternational Olympiad in Informatics
International Olympiad in Informatics
->
International Cin InformaticsOOlympiad W
To make matters more difficult, the cows can apply their encryption scheme several times, by again encrypting the string that results from the previous encryption. One night, Farmer John's cows receive such a multiply-encrypted message. Write a program to compute whether or not the non-encrypted original message could have been the string:
Begin the Escape execution at the Break of Dawn
I am using backtracking to solve this problem, but in the sixth test case:
" BCC execuO the EsCinCaWCCreaOpWtiOn at OCDOcOWaOegCeWtheOW BWoWk of Wwn "
where the answer is actually 0 but my program tries all the possibilities so its timing out.
Here are the optimizations I have tried
1. The part of the encoded message before the first 'C' should match the input string.
2. The part of the encoded message after the last 'W' should match the input string
3. All the substrings in the encoded message between any two letter from 'C','O','W' must be substrings of the input string.
4. At any point of the string the number of Os must be at least as much as the number of Ws and the number of Cs must be at least as much as the number of Os.
I am using C strings (char arrays), I tried switching to C++ and used std::set to store the visited string so that I dont visit them again.
But still the program is timing out on test case 6. I don't thing there is any other algorithm to solve this problem, but I think I am missing some other optimizations.
Here is my code for this problem:
http://ideone.com/2fHCM7. Any help would be greatly appreciated.