Under construction

Still being built. Things may change

Crossing the Stone Bridges

Interview

Time limit1sMemory limit128 MB

Summary
Count ways to match a scroll string to positions across two parallel bridge strings, alternating bridges and strictly increasing positions.
Level

Medium5 of 10

Topics
Dynamic programming, String
Solved
No attempts yet

Problem

An expedition must cross two parallel stone bridges to obtain a ring. One bridge is the , and the other is the .

The two bridges always have the same length. Each stone contains one of the characters R, I, N, G, and S. The table below shows one bridge pair of length 6.

Bridge123456
Demon Stone BridgeRINGSR
Angel Stone BridgeGRGGNS

A magic scroll lists the characters that must be stepped on in order while crossing the bridges. If the expedition breaks this order, the bridges collapse.

A valid crossing must satisfy all of the following rules.

  1. Movement is only from the starting side to the finishing side, that is, from left to right.
  2. Every character written on the scroll must be stepped on in the given order.
  3. The chosen bridge must alternate between the and the at every step. The first stone may be on either bridge.
  4. Each next stone must be strictly to the right of the previous stone. Moving at least one column is enough, and any number of stones may be skipped.

For the bridge pair shown above, if the scroll is RGS, there are exactly 3 valid crossing methods. Given the scroll string and the two bridge strings, compute the total number of valid crossing methods.

Input

The first line contains the string written on the magic scroll. It consists only of R, I, N, G, and S, and its length is between 1 and 20 inclusive.

The second and third lines contain the strings written on the and the , respectively. The two strings have the same length, and that length is between 1 and 100 inclusive.

Output

Print the number of ways to cross the bridges while following the scroll in order. If there is no valid way, print 0.

For every test case, the answer is at most 2^31 - 1.

Examples3

  1. Example 1

    Input
    RGS
    RINGSR
    GRGGNS
    
    Expected output
    3
    
  2. Example 2

    Input
    RINGS
    SGNIRSGNIR
    GNIRSGNIRS
    
    Expected output
    0
    
  3. Example 3

    Input
    GG
    GGGGRRRR
    IIIIGGGG
    
    Expected output
    16