This page is still under construction.

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

Cowlphabet

Time limit1sMemory limit128 MB

Summary
Count valid words over 52 letters with exactly U uppercase and L lowercase letters, given the allowed adjacent letter pairs, modulo 97654321.
Level

Medium7 of 10

Topics
Dynamic programming, Combinatorics, Graph, Matrix
Solved
No attempts yet

Problem

Like all bovines, Farmer John's cows speak the peculiar 'Cow' language. As in many languages, each word in Cow is a sequence of uppercase and lowercase letters (A–Z and a–z). A word is valid if and only if every ordered pair of adjacent letters (the earlier letter followed by the later one) is a valid pair.

Ever worried that his cows are plotting against him, Farmer John recently tried to eavesdrop on their conversation and overheard a single word before the cows noticed him. Cow is spoken so quickly, and its sounds are so strange, that all he could perceive was the total number of uppercase letters UU (1≤U≤2501 \le U \le 250) and the total number of lowercase letters LL (1≤L≤2501 \le L \le 250) in that word.

Farmer John knows all PP (1≤P≤2001 \le P \le 200) valid ordered pairs of adjacent letters in Cow. He wants to know how many different valid words are consistent with this limited data. Because the count can be very large, report it modulo 9765432197654321.

Input

  • Line 1: Three space-separated integers UU, LL, and PP.
  • Lines 2 through P+1P+1: Two letters (each may be uppercase or lowercase) describing one valid ordered pair of adjacent letters — the first letter may be immediately followed by the second.

Output

  • Line 1: A single integer — the number of valid words consistent with Farmer John's data, taken modulo 9765432197654321.

Notes

  • A word is an ordered sequence of letters, and the same letter may appear multiple times.
  • UU and LL are the totals over the whole word; the uppercase and lowercase letters may sit in any positions.
  • Two words are different whenever their letter sequences differ.
  • Since U≥1U \ge 1 and L≥1L \ge 1, every word has length at least 2, so each letter it contains belongs to at least one adjacent pair.

Examples5

  1. Example 1

    Input
    2 2 7
    AB
    ab
    BA
    ba
    Aa
    Bb
    bB
    
    Expected output
    7
    
  2. Example 2

    Input
    1 1 1
    Aa
    
    Expected output
    1
    
  3. Example 3

    Input
    1 1 1
    aA
    
    Expected output
    1
    
  4. Example 4

    Input
    1 1 1
    AB
    
    Expected output
    0
    
  5. Example 5

    Input
    2 2 2
    Aa
    aA
    
    Expected output
    2