#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long ll; typedef vector VI; typedef pair PII; #define REP(i,s,t) for(int i=(s);i<(t);i++) #define FILL(x,v) memset(x,v,sizeof(x)) const int INF = (int)1E9; #define MAXN 1000005 using namespace std; int hashPair(PII p) { return (p.first * 127 + 999937) ^ p.second; } struct PIIHash { size_t operator()(PII p) const { return hashPair(p); } size_t operator()(pair p) const { return hashPair(PII(hashPair(p.first), hashPair(p.second))); } }; ll A[2] = { 234234234, 987654321 }, Apow[2][MAXN]; int P[2] = { 1000000007, 1000000009 }; int hstr[2][MAXN]; void init() { REP(t, 0, 2){ Apow[t][0] = 1; REP(i, 1, MAXN) Apow[t][i] = Apow[t][i - 1] * A[t] % P[t]; } } void hashit(string &s){ int n = s.size(); REP(t, 0, 2){ REP(i, 0, n){ hstr[t][i] = (i ? hstr[t][i - 1] : 0) * A[t] % P[t] + (s[i] - 'a' + 1); if (hstr[t][i] >= P[t]) hstr[t][i] -= P[t]; } } } PII gethash(int l, int r){ int h[2] = {}; REP(t, 0, 2){ h[t] = P[t] + hstr[t][r] - (l ? hstr[t][l - 1] : 0) * Apow[t][r - l + 1] % P[t]; if (h[t] >= P[t]) h[t] -= P[t]; } return PII(h[0], h[1]); } int main() { init(); int n, q; cin >> n >> q; unordered_map, int, PIIHash> preAndSufCnt; unordered_map preCnt, sufCnt; REP(i,0,n) { string s; cin >> s; hashit(s); int len = s.size(); REP(j,1,len+1) { PII ph = gethash(0, j - 1); PII sh = gethash(len - j, len - 1); preCnt[ph]++; sufCnt[sh]++; preAndSufCnt[make_pair(ph, sh)]++; } } while (q--) { string t, p, q; cin >> t >> p >> q; int len = p.size(); hashit(p); PII ph = gethash(0, len - 1); hashit(q); PII sh = gethash(0, len - 1); int ans; if (t == "AND") ans = preAndSufCnt[make_pair(ph, sh)]; else if (t == "OR") ans = preCnt[ph] + sufCnt[sh] - preAndSufCnt[make_pair(ph, sh)]; else ans = preCnt[ph] + sufCnt[sh] - 2 * preAndSufCnt[make_pair(ph, sh)]; cout << ans << endl; } return 0; }