I didn't understand how can i figure out the ans from the counts or number of recipe. |
Each recipe consists of a string of vowels. You're looking for pairs of strings that contain all the vowels between them.
So the only thing that matters about a particular recipe is whether it does or does not contain the various vowels. Let's encode that into a binary number:
4 3 2 1 0 Bit number
u o i e a Corresponding letter |
We'll set the bit to 1 if the letter is present and 0 if it is not.
Example: recipe aaeeeeaeaoae
This contains letters a, e, and o So the encoding is:
And 01011 in binary is 8+2+1=11 in decimal.
This is exactly the encoding that
salem c's function does.
Now every recipe that contains only a,e and o will encode to 11. You can count those up. Let's suppose there 37 of them.
Those recipes lack letters u and i, so for Chef to like a meal, the other recipe must contain u and i. Suppose there are 82 recipies that contain only u and i. That means that all 37 recipes containing a,e, and o can combine with all 82 recipes containing u and i. That's a total of 37*82=3034 recipes.
Since any possible recipe encodes to a a 5-bit number, there are at most 2
5=32 possible encodings. However, notice that encoding 0 means that none of the bits are set, which can only happen of the string is empty. So encoding 0 isn't possible. Therefore there are 31 possible encodings.
Back to the example. I showed that recipes with a,e, and o can combine with recipes with u and i, but those aren't the only recipes that they can combine with. For example, they can also combine with recipes that have a, i and u, or i, o, and u. In fact, they can combine with ANY recipe that contains i and u.
This where some binary operations come in handy. Once two recipes are encoded, it's easy to see if they combine to something tasty. You just have to see if they have all 5 bits set between them. And that's a simple binary or operation (
|
in C++).
So the algorithm is simple:
1. Encode the recipes to their corresponding number. Count up how many recipes encode to each number.
2. For each pair of encodings, if ORing the encodings together gives you all 5 bits set (i.e., if encoding1 | encoding2 == 31) then all combinations of those encodings are tasty. There are count1*count2 possible combinations of those counts.
So it takes O(n) time to encode the strings. Then it takes O(32*31) time to check each pair of encodings. So the overall time is O(n+32*31) = O(n+constant) = O(n).
The whole problem is just an exercise in the use of binary numbers.