题意:要你找到主串中每个模式串的个数。
思路:题目都没说是多组数据,结果没while(~)直接WA了,和上一题差不多,可以用map或者开个数组储存。指针要记得回收内存,不然MLE。
#include<cstdio>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cstring>
#include<string>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#define ll long long
const int maxn = 5000000+5;
const int maxm = 100000+5;
const int MOD = 1e7;
const int INF = 0x3f3f3f3f;
const int kind = 130;
const char baset = 0;
using namespace std;
struct Trie{
Trie *next[kind];
Trie *fail; //失配值
int sum; //以此为单词结尾的个数
int id;
Trie(){
sum = 0;
memset(next,NULL,sizeof(next));
fail = NULL;
id = 0;
}
};
Trie *root;
queue<Trie *> Q;
int head,tail,record[1005];
//map<int,int> record;
void Insert(char *s,int id){
Trie *p = root;
for(int i = 0;s[i];i++){
int x = s[i] - baset;
if(p ->next[x] == NULL){
p ->next[x] = new Trie();
}
p = p ->next[x];
}
p ->sum++;
p ->id = id;
}
void del(Trie *p){
if(p == NULL) return;
for(int i = 0;i < kind;i++){
if(p ->next[i])
del(p ->next[i]);
}
delete p;
}
void buildFail(){
while(!Q.empty()) Q.pop();
Q.push(root);
Trie *p,*temp;
while(!Q.empty()){
temp = Q.front();
Q.pop();
for(int i = 0;i < kind;i++){
if(temp ->next[i]){
if(temp == root){
temp ->next[i] ->fail = root;
}
else{
p = temp ->fail;
while(p){
if(p ->next[i]){
temp ->next[i] ->fail = p ->next[i];
break;
}
p = p ->fail;
}
if(p == NULL) temp ->next[i] ->fail = root;
}
Q.push(temp ->next[i]);
}
}
}
}
void ac_automation(char *ch){
Trie *p = root;
int len = strlen(ch);
for(int i = 0;i < len;i++){
int x = ch[i] - baset;
while(!p ->next[x] && p != root)
p = p ->fail;
p = p ->next[x];
if(!p) p = root;
Trie *temp = p;
while(temp != root){
if(temp ->id > 0) record[temp ->id]++;
temp = temp ->fail;
}
}
}
char ch[1005][55];
char s[2000005];
int main(){
int n,m,x;
while(scanf("%d",&n) != EOF){
root = new Trie();
memset(record,0,sizeof(record));
for(int i = 1;i <= n;i++){
scanf("%s",ch[i]);
Insert(ch[i],i);
}
buildFail();
scanf("%s",s);
ac_automation(s);
for(int i = 1;i <= n;i++){
if(record[i] > 0)
printf("%s: %d\n",ch[i],record[i]);
}
del(root);
}
return 0;
}