This page is still under construction.

Parts of this page are still being built. What you see may change.

Cow Yahtzee

Time limit1sMemory limit128 MB

Summary
Count ordered rolls of N dice with S sides that satisfy at least one OR-ed expression, where each expression ANDs forms like WxR meaning at least W copies of face R.
Level

Medium7 of 10

Topics
Combinatorics, Math, Brute force, Bit manipulation
Solved
No attempts yet

Problem

The cows are playing a version of Yahtzee, the dice-rolling game. They roll NN dice, each having SS sides (faces numbered 11 through SS). They want to know, over every possible roll, how many rolls satisfy a given criterion (such as "contains three 2's" or "contains one 2 and two 3's").

A roll is an ordered sequence of the NN dice results. For example, the complete set of rolls for three two-sided dice is:

{1,1,1; 1,1,2; 1,2,1; 1,2,2; 2,1,1; 2,1,2; 2,2,1; 2,2,2}.

Each criterion is built from a basic form that expresses "want at least WW copies of result RR", written as:

WxR

where 0≤W≤N0 \le W \le N and 1≤R≤S1 \le R \le S.

You are given EE expressions. Each expression is 11 to 1010 basic forms joined by +, where + means "and": a roll satisfies the expression only if it satisfies every one of its basic forms. The EE expressions are combined with an inclusive or: a roll counts if it satisfies at least one of the expressions.

For example, the two expressions

3x5
1x3+2x4

mean "at least three 5's, OR (at least one 3 and at least two 4's)". Some rolls of four five-sided dice that satisfy them are: 5,5,5,1; 4,5,5,5; 3,4,4,2; 3,4,4,3; 3,4,4,5; 4,4,5,3.

Count how many of the SNS^N possible rolls satisfy at least one expression.

Constraints: 1≤N≤201 \le N \le 20, 1≤S≤81 \le S \le 8, 1≤E≤201 \le E \le 20, each expression has 11 to 1010 basic forms, 0≤W≤N0 \le W \le N, and 1≤R≤S1 \le R \le S. The total number of dice combinations (SNS^N) never exceeds 1,512,768.

Input

  • Line 1: three space-separated integers NN, SS, and EE.
  • Lines 2 to E+1E+1: line i+1i+1 contains expression ii, in the format described above.

Output

  • A single integer: the number of rolls, out of all SNS^N combinations, that satisfy at least one expression.

Examples1

  1. Example 1

    Input
    4 5 2
    3x5
    1x3+2x4
    
    Expected output
    63