luogu#P5196. [USACO19JAN] Cow Poetry G

[USACO19JAN] Cow Poetry G

Background

USACO January 2019 Gold, Problem 1.

Problem Description

Unknown to Farmer John, Bessie is also enthusiastic about sponsoring artistic creation. Recently, she started studying many great poets, and now she wants to try writing some poems of her own.

Bessie knows NN words (1N50001 \leq N \leq 5000) and wants to use them in her poems. She has computed the length of each word she knows in syllables, and she has also divided these words into different "rhyme classes". Each word rhymes only with other words in the same rhyme class.

Each poem Bessie writes has MM lines (1M1051 \leq M \leq 10^5). Each line must consist of exactly KK syllables (1K50001 \leq K \leq 5000). In addition, Bessie's poem must follow a specified rhyme scheme.

Bessie wants to know how many different poems she can write that satisfy these constraints.

Input Format

The first line contains NN, MM, and KK.

The next NN lines each contain two integers sis_i (1siK1 \leq s_i \leq K) and cic_i (1ciN1 \leq c_i \leq N). This indicates a word that Bessie knows with length sis_i (in syllables) and rhyme class cic_i.

The last MM lines describe the rhyme scheme Bessie wants, each containing an uppercase letter eie_i. All lines whose rhyme scheme letter equals eie_i must end with a word from the same rhyme class. Lines with different eie_i values are not required to end with words from different rhyme classes.

Output Format

Output the number of different poems Bessie can write that satisfy these constraints. Since this number may be very large, output it modulo 1,000,000,0071,000,000,007.

3 3 10
3 1
4 1
3 2
A
B
A
960

Hint

In this example, Bessie knows three words. The first two words rhyme and have lengths of three and four syllables, respectively. The last word has length three syllables and does not rhyme with any other word. She wants to write a three-line poem, where each line has ten syllables, and the first and last lines rhyme. There are 960960 such poems. One valid poem is (where 1,2,31,2,3 represent the first, second, and third words): 121 123 321\text{121 123 321}.

Translated by ChatGPT 5