PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#QHD0000083. Thơ gieo vần (Cow Poetry)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

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 MM lines. Each line must contain exactly KK syllables. She knows NN distinct words; word ii has sis_i syllables and belongs to rhyme class cic_i. 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 MM 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 109+710^9+7. If no valid line can be formed, print 00.

Input

The first line contains N,M,KN,M,K. Each of the next NN lines contains si,cis_i,c_i, the syllable count and rhyme class of word ii. The final MM 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 109+710^9+7.

Subtasks

  • Subtask 1 (20 points): 1≤N≤71\le N\le7, 1≤M≤61\le M\le6, 1≤K≤71\le K\le7, 1≤si≤K1\le s_i\le K, 1≤ci≤N1\le c_i\le N.

  • Subtask 2 (30 points): 1≤N≤2001\le N\le200, 1≤M≤20001\le M\le2000, 1≤K≤4001\le K\le400, 1≤si≤K1\le s_i\le K, 1≤ci≤N1\le c_i\le N.

  • Subtask 3 (50 points): 1≤N≤50001\le N\le5000, 1≤M≤1051\le M\le10^5, 1≤K≤50001\le K\le5000, 1≤si≤K1\le s_i\le K, 1≤ci≤N1\le c_i\le N.

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.