/*
* Author: Geeza
*/

#include <bits/stdc++.h>

#define ld long double
#define ll long long
#define pb push_back
#define fin(a, n) for(int i = a; i < n; i++)
#define fjn(a, n) for(int j = a; j < n; j++)
#define all(a) a.begin(),a.end()
#define allr(a) a.rbegin(),a.rend()
#define FAST ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr)

using namespace std;

const double PI = acos(-1);
const int N = 2e6+10, M = 1e3+10;
const ll oo = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9+7, inf = 1e6;
const ld EPS = 1e-9;

string di[] = {"D","L", "U", "R", "UL", "UR", "DL", "DR"};
int dx[] = {+1, +0, +0, -1, -1, -1, +1, +1};
int dy[] = {+0, -1, +1, +0, -1, +1, -1, +1};
char dc[] = {'D', 'L', 'R', 'U'};

vector<int> mp, mp2;
struct node {
    node *nxt[10];
    int cnt, end;

    node() {
        cnt = 0, end = 0;
        memset(nxt, 0, sizeof nxt);
    }
};

struct Trie {
    node *root;

    Trie() {
        root = new node();
    }

    void insert(string s) {
        node *cur = root;
        for (int i = 0; i < s.size(); i++) {
            if (!cur->nxt[s[i]-'0']) cur->nxt[s[i]-'0'] = new node();
            cur->cnt++;
            cur = cur->nxt[s[i]-'0'];
        }
        cur->cnt++;
        cur->end++;
    }

    ll query(string s) {
        node *cur = root;
        ll ret = 0;
        bool lz = true;
        for (int i = 0; i < s.size(); i++) {
            if (lz && s[i]-'0' > 0) lz = false;
            if (!cur->nxt[s[i] - '0'] || cur->nxt[s[i] - '0']->cnt == 0) return 0;
            if (!lz){
                for (int x = mp[s[i]-'0']-1; x >= 0; x--) {
                    if (!cur->nxt[mp2[x]] || cur->nxt[mp2[x]]->cnt == 0)continue;
                    ret += cur->nxt[mp2[x]]->cnt;
                }
            }
            cur = cur->nxt[s[i] - '0'];
        }
        return ret;
    }
};

void solve() {
    mp.assign(10, 0);
    mp2.assign(10, 0);
    ll n; cin >> n;
    vector<string> v(n);
    fin(0, n) {
        cin >> v[i];
        v[i] = string(19-v[i].size(), '0') + v[i];
    }
    Trie tr;
    fin(0, n) tr.insert(v[i]);
    ll q; cin >> q;
    while (q--) {
        fin(0, 10) {
            int x; cin >> x;
            mp[x] = i;
            mp2[i] = x;
        }
        string x; cin  >> x;
        x = string(19-x.size(), '0')+x;
        cout << tr.query(x) << "\n";
    }
}

int main() {
    FAST;
#ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
#endif
    int tt = 1; //cin >> tt;
    while(tt--){
        solve();
    }
    return 0;
}