Under construction

Still being built. Things may change

Redistributing Gifts

Time limit2sMemory limit1024 MB

Summary
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 NN gifts labeled 1…N1\ldots N for his NN cows, also labeled 1…N1\ldots N (1≤N≤181\le N\le 18). Each cow has a wishlist, which is a permutation of all NN gifts. A cow prefers gifts that appear earlier in her list over gifts that appear later.

FJ was lazy and just assigned gift ii to cow ii for all ii. 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 QQ breed strings of length NN (1≤Q≤min⁡(105,2N)1\le Q\le \min(10^5,2^N)). For each string, count the reassignments that are consistent with it.

Input

The first line contains NN. The next NN lines each contain the preference list of one cow, a permutation of 1…N1\dots N. The next line contains QQ. The final QQ lines each contain a breed string of length NN 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.

Examples1

  1. Example 1

    Input
    4
    1 2 3 4
    1 3 2 4
    1 2 3 4
    1 2 3 4
    5
    HHHH
    HHGG
    GHGH
    HGGG
    GHHG
    
    Expected output
    2
    1
    1
    2
    2