#QHD0000083. Thơ gieo vần (Cow Poetry)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Thơ gieo vần (Cow Poetry)
Cow Poetry
Source: USACO
Version: Phuoc Hung OJ Extended
Problem Statement
Bessie wants to compose a poem of exactly lines. Each line must contain exactly syllables. She knows distinct words; word has syllables and belongs to rhyme class . Two words rhyme if and only if their rhyme classes agree. A word can be repeated arbitrarily, including within a line. A line's syllable count is the sum of the syllable counts of its words. Word order matters.
The rhyme scheme is a sequence of uppercase letters from A to Z, one letter per line. Lines with the same letter must end with words from the same rhyme class. Different letters may use the same rhyme class. Only the last word of a line determines its rhyme class. Two poems are different if at least one word position differs in some line.
Count the valid poems and print the result modulo . If no valid line can be formed, print .
Input
The first line contains . Each of the next lines contains , the syllable count and rhyme class of word . The final lines each contain one uppercase letter, describing the corresponding line of the rhyme scheme.
Output
Print a single integer, the number of valid poems modulo .
Subtasks
-
Subtask 1 (20 points): , , , , .
-
Subtask 2 (30 points): , , , , .
-
Subtask 3 (50 points): , , , , .
Examples
Example 1
Input
3 3 10
3 1
4 1
3 2
A
B
A
Output
960
Explanation: The rhyme class is fixed for both A-lines, while the B-line may independently use either class; syllable lengths and word order produce 960 valid poems.
Example 2
Input
2 2 2
1 1
2 2
A
A
Output
2
Explanation: Each line is either the first word repeated or the second word alone. The equal-letter requirement leaves exactly two possible poems.