字典树建树,然后dfs搜索即可
1 //#pragma comment(linker, "/STACK:1677721600") 2 #include <map> 3 #include <set> 4 #include <stack> 5 #include <queue> 6 #include <cmath> 7 #include <ctime> 8 #include <vector> 9 #include <cstdio> 10 #include <cctype> 11 #include <cstring> 12 #include <cstdlib> 13 #include <iostream> 14 #include <algorithm> 15 using namespace std; 16 #define INF 0x3f3f3f3f 17 #define inf (-((LL)1<<40)) 18 #define lson k<<1, L, (L + R)>>1 19 #define rson k<<1|1, ((L + R)>>1) + 1, R 20 #define mem0(a) memset(a,0,sizeof(a)) 21 #define mem1(a) memset(a,-1,sizeof(a)) 22 #define mem(a, b) memset(a, b, sizeof(a)) 23 #define FIN freopen("in.txt", "r", stdin) 24 #define FOUT freopen("out.txt", "w", stdout) 25 #define rep(i, a, b) for(int i = a; i <= b; i ++) 26 #define dec(i, a, b) for(int i = a; i >= b; i --) 27 28 template<class T> T MAX(T a, T b) { return a > b ? a : b; } 29 template<class T> T MIN(T a, T b) { return a < b ? a : b; } 30 template<class T> T GCD(T a, T b) { return b ? GCD(b, a%b) : a; } 31 template<class T> T LCM(T a, T b) { return a / GCD(a,b) * b; } 32 33 //typedef __int64 LL; 34 typedef long long LL; 35 const int MAXN = 100000 + 100; 36 const int MAXM = 110000; 37 const double eps = 1e-8; 38 LL MOD = 1000000007; 39 40 int t, n, m; 41 char str[10], s1[5005][10]; 42 int tree[30010][27], s, ans; 43 bool val[30010];//val[i] = 1表示是某个字符串的尾节点 44 vector<int>e[12]; 45 46 void init() { 47 int cnt = 5; 48 rep (i, 'a', 'z') { 49 cnt += 1 + (i == 's' || i == 'z' ? -1 : 0); 50 e[cnt / 3].push_back(i - 'a'); 51 } 52 } 53 54 void insert_to_tree(char* str) 55 { 56 int u = 0; 57 for(int i = 0; str[i]; i ++) 58 { 59 int c = str[i] - 'a'; 60 if(!tree[u][c]) 61 { 62 tree[u][c] = ++s; 63 val[s] = 0; 64 } 65 u = tree[u][c]; 66 } 67 val[u] = 1; 68 } 69 70 void dfs(int u, int k, char *s, int n) { 71 ans += val[u] && k == n; 72 int p = s[k] - '0', sz = e[p].size(); 73 rep (i, 0, sz - 1) { 74 int v = e[p][i]; 75 if(tree[u][v] && k < n) 76 dfs(tree[u][v], k + 1, s, n); 77 } 78 } 79 80 int main() 81 { 82 // FIN; 83 init(); 84 cin >> t; 85 while(t--) { 86 s = 0; 87 mem0(tree); mem0(val); 88 scanf("%d %d%*c", &n, &m); 89 rep (i, 0, n - 1) scanf("%s", s1[i]); 90 rep (i, 1, m) { 91 scanf("%s", str); 92 insert_to_tree(str); 93 } 94 rep (i, 0, n - 1) { 95 ans = 0; 96 dfs(0, 0, s1[i], strlen(s1[i])); 97 cout << ans << endl; 98 } 99 } 100 return 0; 101 }