This page is still under construction.

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

GREAT + SWERC = PORTO

Time limit2sMemory limit256 MB

Summary
Count the assignments of distinct digits to letters that make the word sum correct with nonzero leading letters.
Level

Medium5 of 10

Topics
Backtracking, Brute force
Solved
No attempts yet

Problem

We wanted a good SWERC in Porto this year and tried several ideas. One of them was turning the name into a word addition puzzle like the classic SEND+MORE=MONEY. In a word addition each letter stands for a single digit from 0 to 9, and substituting those digits has to make the addition correct. Different letters get different digits, and the leftmost letter of a word cannot be zero. In particular, a term made of a single letter cannot be zero.

Solving GREAT+SWERC=PORTO means giving G, S and P positive digits and giving R, E, A, T, W, C, O digits as well, so that every letter has a different digit and the sum is correct. Unlike SEND+MORE=MONEY, which has a single solution, GREAT+SWERC=PORTO has six solutions.

  • T=7, E=3, W=9, G=1, A=0, P=4, S=2, C=8, R=6, O=5
  • T=7, E=3, W=9, G=2, A=0, P=4, S=1, C=8, R=6, O=5
  • T=8, E=5, W=1, G=3, A=7, P=9, S=6, C=4, R=0, O=2
  • T=8, E=5, W=1, G=6, A=7, P=9, S=3, C=4, R=0, O=2
  • T=9, E=5, W=2, G=1, A=8, P=7, S=6, C=4, R=0, O=3
  • T=9, E=5, W=2, G=6, A=8, P=7, S=1, C=4, R=0, O=3

Having more than one solution makes it a poor puzzle to solve by hand, but a program handles it easily.

Given a word addition puzzle, compute the number of solutions. The count can be zero.

Input

The first line contains an integer nn. Each of the next nn lines contains one word of at most 10 letters. The first n−1n-1 words are the terms to be added and the last line is the result. Words contain capital letters only. Words of different lengths are aligned to the right. For instance, in SEND+MORE=MONEY the D of the first word and the E of the second word sit in the same column as the Y of the last word. The length of the last word is at least the maximum length of the preceding words, and a puzzle involves at most ten distinct letters.

Output

Print a single line with one integer, the number of solutions of the given word addition puzzle.

Constraints

  • 3≤n≤103 \le n \le 10
  • Each word has at most 10 letters, all capital.
  • A puzzle involves at most 10 distinct letters.

Examples3

  1. Example 1

    Input
    3
    GREAT
    SWERC
    PORTO
    
    Expected output
    6
    
  2. Example 2

    Input
    3
    SEND
    MORE
    MONEY
    
    Expected output
    1
    
  3. Example 3

    Input
    5
    TOO
    GOOD
    TO
    BE
    TRUE
    
    Expected output
    93