Redistributing Gifts
Time limit2sMemory limit1024 MB
Given each cow's preference permutation and breed strings, count the gift reassignments per string where every cow keeps her gift or gets a preferred one within her breed.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Bit manipulation, Combinatorics
- Solved
- No attempts yet
Problem
Farmer John has gifts labeled for his cows, also labeled (). Each cow has a wishlist, which is a permutation of all gifts. A cow prefers gifts that appear earlier in her list over gifts that appear later.
FJ was lazy and just assigned gift to cow for all . Now the cows have gathered and decided to reassign the gifts. After reassignment, every cow must end up with either the same gift she originally had or a gift she prefers over it.
There is one more constraint. A gift may only be reassigned to a cow if the gift was originally assigned to a cow of the same breed. Each cow is either a Holstein or a Guernsey. You are given breed strings of length (). For each string, count the reassignments that are consistent with it.
Input
The first line contains . The next lines each contain the preference list of one cow, a permutation of . The next line contains . The final lines each contain a breed string of length made only of the characters G and H. No breed string occurs more than once.
Output
For each breed string, print the number of reassignments consistent with it on a new line.
Hint
In the sample, the first breed string allows two reassignments. The first is the original assignment: cow 1 gets gift 1, cow 2 gets gift 2, cow 3 gets gift 3, and cow 4 gets gift 4. The second has cow 1 with gift 1, cow 2 with gift 3, cow 3 with gift 2, and cow 4 with gift 4. For the second breed string, the only consistent reassignment is the original assignment.