<|instruction|>
Solve the below problem. The solution should start with an abridged problem statement. Then key observations. Then full solution based on the observations. Then C++ and Python implementations with comments.

201. Non Absorbing DFA
time limit per test: 0.25 sec.
memory limit per test: 65536 KB
input: standard
output: standard



In the theory of compilers and languages finite state machines, also known as finite automata are widely used. Deterministic finite automation (DFA) is an ordered set <Σ, U, s, T, φ> where Σ is the finite set called input alphabet, U is the finite set of states, s from U is the initial state, T subset of U is the set of terminal states and φ : U × Σ → U is the transition function.

The input of the automation is the string α over Σ. Initially the automation is in state s. Each step it reads the first character c of the input string and changes its state to φ(u, c) where u is the current state. After that the first character of the input string is removed and the step repeats. If when its input string is empty the automation is in the terminal state, it is said that it accepts the initial string α, in the other case it rejects it.

In some cases to simplify the automation the concept of nonabsorbing edges is introduced. That is, in addition to φ the function χ : U × Σ → {0, 1} is introduced and when making a transition from some state u with some character c, the leading character is removed from the input string only if χ(u, c) = 0. If χ(u, c) = 1, the input string is kept intact and next transition is performed with the new state and the same character.

It is said that such automation accepts some string α if after a number of steps it transits to the terminal state and the input string becomes empty.

Your task is given the DFA with nonabsorbing edges to compute the number of strings of the given length N that it accepts.

Input

The first line of the input file contains Σ — a subset of the English alphabet, several different small letters. Next line contains K = | U | — the number of states of the automation (1 ≤ K ≤ 1000). Let states be numbered from 1 to K. Next line contains S (1 ≤ S ≤ K) — the initial state, followed by L = | T | — the number of terminal states and then L different integer numbers ranging from 1 to K — the numbers of terminal states.

Next K lines contain | Σ | integer numbers each and define φ. Next K lines define χ in a similar way. The last line of the input file contains N (1 ≤ N ≤ 60).

Output

Output the only number — the number of different strings of length N over Σ that the given DFA accepts.

In the given example the two strings accepted by the automation are ``aaa'' and ``abb''.

Sample test(s)

Input
ab
2
1 1 2
2 1
1 2
0 1
0 0
3

Output
2

Author:	Andrew Stankevich
Resource:	Petrozavodsk Summer Trainings 2003
Date:	2003-08-23

<|response|>
1. Abridged Problem Statement  
We have a deterministic finite automaton (DFA) extended with “non-absorbing” edges. Formally:  
• Alphabet Σ of size σ.  
• States U = {1…K}, initial state S, terminal states T.  
• Transition φ: U×Σ→U, and absorption flag χ: U×Σ→{0,1}.  
  – If χ(u,c)=0 the input character c is consumed; if χ(u,c)=1 it is not consumed.  
A string is accepted if, after a finite number of steps, the automaton reaches a terminal state and the input is empty. Count how many distinct strings of length exactly N over Σ are accepted. Constraints: K≤1000, N≤60, σ≤26.

2. Key Observations  
– A non-absorbing edge may move between states without consuming the current character, possibly forming loops that never consume it. Any string that attempts to use such a loop can never finish consuming N characters and accept.  
– We can “collapse” each (state u, letter c) into one effective absorbing move: follow χ=1 edges repeatedly until you hit a state that consumes c (χ=0) or detect a cycle of χ=1 edges (infinite loop).  
– After collapsing, every letter consumption becomes a single transition: from u reading c you end up in some state v=φ(a,c), where a is the state that actually consumes c.  
– We then do a standard DP over the number of consumed characters: dp[i][u] = number of length-i prefixes that lead to state u.  

3. Full Solution Approach  
Step A. Read input: Σ, K, S, terminal states T, tables φ and χ, and N. Convert states to 0-based.  
Step B. Precompute effective transitions:  
  Create an array trans[K][σ], initially marked UNVISITED.  
  Define a DFS procedure dfs(u,c):  
    if χ[u][c]==0 then trans[u][c]=u (consumes here) and return.  
    if trans[u][c] is being visited (mark VISITING) then we found a χ=1 cycle ⇒ set trans[u][c] = -1 (infinite loop) and return.  
    otherwise mark trans[u][c]=VISITING, let v=φ[u][c], call dfs(v,c), then set trans[u][c] = trans[v][c].  
  Run dfs(u,c) for all u in [0..K−1], c in [0..σ−1].  
Step C. Dynamic Programming:  
  Let dp be a (N+1)×K table of big integers, all zero. Set dp[0][S]=1.  
  For i from 0 to N−1, for each state u, if dp[i][u]>0 then for each letter c:  
    a = trans[u][c]; if a<0 skip (infinite loop).  
    v = φ[a][c];  
    dp[i+1][v] += dp[i][u].  
Step D. The answer is sum(dp[N][t]) over all terminal states t. Print it.  

Time complexity: O(K·σ + N·K·σ). N≤60, K≤1000, σ≤26 is fine.  

4. C++ Implementation with Detailed Comments  
```cpp
#include <bits/stdc++.h>
using namespace std;

// Simple Big Integer base 1e9
struct BigInt {
    static const int BASE = 1000000000;
    vector<int> d;  // least-significant block first
    BigInt(long long x = 0) { 
        if (x==0) d = {0};
        else {
            while (x>0) {
                d.push_back(x % BASE);
                x /= BASE;
            }
        }
    }
    // Addition
    void add(const BigInt &o) {
        long long carry = 0;
        int n = max(d.size(), o.d.size());
        d.resize(n, 0);
        for (int i = 0; i < n || carry; i++) {
            if (i == d.size()) d.push_back(0);
            long long sum = carry + d[i] + (i < (int)o.d.size() ? o.d[i] : 0);
            d[i] = sum % BASE;
            carry = sum / BASE;
        }
        // remove leading zeros?
    }
    string toString() const {
        string s = "";
        for (int i = d.size()-1; i >= 0; i--) {
            string part = to_string(d[i]);
            if (i < (int)d.size()-1)
                s += string(9 - part.size(), '0') + part;
            else
                s += part;
        }
        return s;
    }
};

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    // 1. Read input
    string alphabet;
    cin >> alphabet;
    int sigma = alphabet.size();

    int K;
    cin >> K;
    int S, L;
    cin >> S >> L;
    --S; // zero-based
    vector<int> terminals(L);
    for(int i=0;i<L;i++){
        cin >> terminals[i];
        --terminals[i];
    }

    vector<vector<int>> phi(K, vector<int>(sigma));
    for(int u=0;u<K;u++){
        for(int c=0;c<sigma;c++){
            cin >> phi[u][c];
            --phi[u][c];
        }
    }
    vector<vector<int>> chi(K, vector<int>(sigma));
    for(int u=0;u<K;u++){
        for(int c=0;c<sigma;c++){
            cin >> chi[u][c];
        }
    }

    int N;
    cin >> N;

    // 2. Precompute effective transitions
    const int UNVIS = -2, VISITING = -3;
    vector<vector<int>> trans(K, vector<int>(sigma, UNVIS));

    function<void(int,int)> dfs = [&](int u, int c){
        if (chi[u][c] == 0) {
            // consumes here
            trans[u][c] = u;
            return;
        }
        if (trans[u][c] == VISITING) {
            // found a cycle of non-absorbing edges
            trans[u][c] = -1;
            return;
        }
        if (trans[u][c] != UNVIS) {
            // already computed
            return;
        }
        // start visiting
        trans[u][c] = VISITING;
        int v = phi[u][c];
        dfs(v, c);
        // inherit result from v
        trans[u][c] = trans[v][c];
    };

    for(int u=0; u<K; u++){
        for(int c=0; c<sigma; c++){
            if (trans[u][c] == UNVIS)
                dfs(u,c);
        }
    }

    // 3. DP table: dp[i][u] = ways to reach u after consuming i chars
    vector<vector<BigInt>> dp(N+1, vector<BigInt>(K, BigInt(0)));
    dp[0][S] = BigInt(1);

    for(int i=0; i<N; i++){
        for(int u=0; u<K; u++){
            // skip if no ways
            if (dp[i][u].d.size()==1 && dp[i][u].d[0]==0) continue;
            for(int c=0; c<sigma; c++){
                int a = trans[u][c];
                if (a < 0) continue;      // infinite loop, skip
                int v = phi[a][c];        // after consuming c
                dp[i+1][v].add(dp[i][u]);
            }
        }
    }

    // 4. Sum up answers in terminal states
    BigInt answer(0);
    for(int t: terminals)
        answer.add(dp[N][t]);

    cout << answer.toString() << "\n";
    return 0;
}
```

5. Python Implementation with Detailed Comments  
```python
import sys
sys.setrecursionlimit(10000)

def main():
    # 1. Read input
    alphabet = sys.stdin.readline().strip()
    sigma = len(alphabet)

    K = int(sys.stdin.readline())
    parts = list(map(int, sys.stdin.readline().split()))
    S = parts[0] - 1             # zero-based
    L = parts[1]
    terminals = [x-1 for x in parts[2:]]

    # φ table
    phi = [None]*K
    for u in range(K):
        row = list(map(int, sys.stdin.readline().split()))
        phi[u] = [x-1 for x in row]

    # χ table
    chi = [None]*K
    for u in range(K):
        chi[u] = list(map(int, sys.stdin.readline().split()))

    N = int(sys.stdin.readline())

    # 2. Precompute effective transitions
    # trans[u][c] = state where c is consumed, or -1 if infinite loop
    UNVIS, VISITING = None, -1
    trans = [[UNVIS]*sigma for _ in range(K)]

    def dfs(u, c):
        if chi[u][c] == 0:
            # consumes here
            trans[u][c] = u
            return
        if trans[u][c] == VISITING:
            # found a non-consuming cycle
            trans[u][c] = -1
            return
        if trans[u][c] is not UNVIS:
            # already resolved
            return
        # mark visiting
        trans[u][c] = VISITING
        v = phi[u][c]
        dfs(v, c)
        trans[u][c] = trans[v][c]

    for u in range(K):
        for c in range(sigma):
            if trans[u][c] is UNVIS:
                dfs(u, c)

    # 3. DP: dp[i][u] = number of ways to reach u after i consumed chars
    dp = [ [0]*K for _ in range(N+1) ]
    dp[0][S] = 1

    for i in range(N):
        for u in range(K):
            ways = dp[i][u]
            if ways == 0:
                continue
            for c in range(sigma):
                a = trans[u][c]
                if a < 0:
                    continue   # infinite loop
                v = phi[a][c]
                dp[i+1][v] += ways

    # 4. Sum over terminal states
    result = sum(dp[N][t] for t in terminals)
    print(result)

if __name__ == "__main__":
    main()
```

Explanation of the Key Steps:  
- We collapse any chain of non-consuming edges into one effective “where will this letter be consumed?” transition, marking those chains that never consume (pure loops) as invalid.  
- With these effective transitions, each input character simply advances the DP by one consumed character, just like in a normal DFA, and we never worry again about χ flags.  
- A final sum over terminal states gives the total number of accepted strings of length N.