传送门
思路:将所有特征码建成一个AC自动机,然后查找就行了,找的时候直接找完也不会超时,因为模式串太短了(不超过50个字符),再长一点可以考虑树DP。
如果用后缀数组的话,我觉得可以
O(NlogM)
(N为串的总长度,M为模式串最长长度)来Build。然后在Height数组里二分答案
O(TlogM)
(T为模式串个数,一次lower_bound,一次upper_bound)即可完成。
还有,出题人太坑,没有说是多组数据。
代码(AC自动机):
#include<stdio.h>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define MAXN 2000005
#define MAXC 26
#define MAXM 1005
#define MAXL 55
int n, root, sz, q[MAXM*MAXL], cnt[1005];
vector<int> arr;
char s[MAXN], word[MAXM][60];
struct Trie {
int nxt[MAXC], fail, id;
} t[MAXM * MAXL];
inline int NewNode() {
++ sz;
memset(t[sz].nxt, 0, sizeof t[sz].nxt);
t[sz].id = t[sz].fail = 0;
return sz;
}
inline void Ins(char *s, int id) {
int len = strlen(s), cur = root;
for(int i = 0; i < len; ++ i) {
if(!t[cur].nxt[s[i]-'A']) t[cur].nxt[s[i]-'A'] = NewNode();
cur = t[cur].nxt[s[i]-'A'];
}
t[cur].id = id;
}
inline void Build() {
int l = 1, r = 0; t[root].id = -1;
for(int i = 0; i < MAXC; ++ i)
if(!t[root].nxt[i]) t[root].nxt[i] = root;
else {
t[ t[root].nxt[i] ].fail = root;
q[++ r] = t[root].nxt[i];
}
while(l <= r) {
int u = q[l ++];
for(int i = 0; i < MAXC; ++ i)
if(!t[u].nxt[i]) t[u].nxt[i] = t[ t[u].fail ].nxt[i];
else {
t[ t[u].nxt[i] ].fail = t[ t[u].fail ].nxt[i];
q[++ r] = t[u].nxt[i];
}
}
}
inline int Query(char *s) {
int len = strlen(s), cur = root, ans = 0;
for(int i = 0; i < len; ++ i) {
if('A' > s[i] || s[i] > 'Z') {cur = root; continue;}
cur = t[cur].nxt[s[i]-'A'];
int tmp = cur;
while(~t[tmp].id) {
if(t[tmp].id) arr.push_back(t[tmp].id);
tmp = t[tmp].fail;
}
}
return ans;
}
int main() {
while(~scanf("%d", &n)) {
sz = 0; root = NewNode();
for(int i = 1; i <= n; ++ i) {
scanf("%s", word[i]);
Ins(word[i], i);
}
arr.clear();
memset(cnt, 0, sizeof cnt);
Build();
scanf("%s", s);
Query(s);
for(int j = 0; j < (int)arr.size(); ++ j)
++ cnt[ arr[j] ];
for(int i = 1; i <= n; ++ i)
if(cnt[i]) printf("%s: %d\n", word[i], cnt[i]);
}
return 0;
}