思路:直接字典树即可。
AC代码
#include <cstdio>
#include <cmath>
#include <cctype>
#include <algorithm>
#include <cstring>
#include <utility>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
#pragma comment(linker, "/STACK:1024000000,1024000000")
#define eps 1e-10
#define inf 0x3f3f3f3f
#define PI pair<int, int>
typedef long long LL;
const int maxn = 26;
struct node{
int cnt;
node *nex[maxn];
node() {
cnt = 0;
for(int i = 0; i < maxn; ++i) nex[i] = NULL;
}
}*root;
void build_tree() {
root = new node();
}
void insert(char *s) {
node *p = root, *q;
for(int i = 0; i < strlen(s); ++i) {
int ind = s[i]-'a';
if(p->nex[ind] == NULL) {
q = new node();
q->cnt++;
p->nex[ind] = q;
}
else {
p->nex[ind]->cnt++;
}
p = p->nex[ind];
}
}
int find(char *s) {
node *p = root;
int n = strlen(s);
for(int i = 0; i < n; ++i) {
int ind = s[i] - 'a';
if(p->nex[ind] == NULL) return 0;
if(i == n-1) {
return p->nex[ind]->cnt;
}
p = p->nex[ind];
}
}
int main() {
build_tree();
int n, m;
char s[15];
scanf("%d", &n);
for(int i = 0; i < n; ++i) {
scanf("%s", s);
insert(s);
}
scanf("%d", &m);
for(int i = 0; i < m; ++i) {
scanf("%s", s);
printf("%d\n", find(s));
}
return 0;
}
如有不当之处欢迎指出!