This page is still under construction.

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

Typing monkey

Time limit1sMemory limit256 MB

Summary
Given per-letter probabilities and two words P and Q, compute the probability that P appears as a substring before Q does.
Level

Medium7 of 10

Topics
Probability, String matching, Matrix
Solved
No attempts yet

Problem

You have a monkey that can work a typewriter. It types lowercase English letters one at a time, without stopping, drawing each letter from a fixed probability distribution, and the keypresses are independent of one another.

You believe the monkey will eventually type out the complete works of Shakespeare. Your friend believes it is more likely to write another novel in the Harry Potter series. To settle the argument, shrink each work down to a single word and compute the probability that one word turns up before the other.

A word is produced the moment it appears as a substring of the letters the monkey has typed so far. Given two words PP and QQ, compute the probability that the monkey produces PP before QQ.

Input

The first line contains the number of test cases TT.

Each test case takes two lines. The first line contains the probabilities pa,pb,…,pzp_a, p_b, \ldots, p_z of the monkey typing each letter from a to z, in that order, separated by single spaces. The second line contains the two strings PP and QQ, separated by one space. Both strings consist of lowercase English letters only.

  • 0<T≤1000 < T \le 100
  • 0≤pα≤10 \le p_\alpha \le 1 and ∑αpα=1\sum_\alpha p_\alpha = 1
  • 0<∣P∣,∣Q∣≤160 < |P|, |Q| \le 16
  • PP and QQ are different.
  • Every letter that occurs in PP or in QQ has probability greater than zero.
  • No input makes the monkey complete PP and QQ at the same moment.

Output

For each test case, print on its own line the probability that the monkey produces PP before QQ. Round the value at the seventh digit after the decimal point and always print exactly six digits after the decimal point.

Examples3

  1. Example 1

    Input
    1
    0.1 0 0 0 0.1 0 0 0.1 0 0 0 0.1 0.1 0 0.1 0.1 0 0.1 0 0.2 0 0 0 0 0 0
    hamlet potter
    
    Expected output
    0.333333
    
  2. Example 2

    Input
    4
    0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0.04 0
    aa ab
    0.6 0.4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    aab abb
    0.6 0.4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    aaa bab
    0.6 0.4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    abab babb
    
    Expected output
    0.500000
    0.789474
    0.587368
    0.768224
    
  3. Example 3

    Input
    3
    0.25 0.75 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    a b
    0.001 0.999 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    a b
    0.2 0.3 0.5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    c a
    
    Expected output
    0.250000
    0.001000
    0.714286