水题不多说 没关freopen WA了一次
代码如下:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
#include <set>
#define sf scanf
#define pf printf
using namespace std;
const int sigma_size = 26;
typedef struct Trie_Node* poi_Node;
struct Trie_Node{
int v;
poi_Node next[sigma_size];
poi_Node fail;
};
poi_Node root;
poi_Node make_node(){
poi_Node cur = new Trie_Node;
cur -> v = 0;
memset(cur -> next,NULL,sizeof(cur -> next));
cur -> fail = NULL;
return cur;
}
void Insert(char* s,int v){
int len = strlen(s);
poi_Node cur = root;
for(int i = 0;i < len;++i){
int idx = s[i] - 'A';
if(cur -> next[idx] == NULL){
cur -> next[idx] = make_node();
}
cur = cur -> next[idx];
}
cur -> v = v;
}
void get_fail(){
queue<poi_Node> q;
q.push(root);
while( !q.empty() ){
poi_Node cur = q.front();q.pop();
for(int i = 0;i < sigma_size;++i){
if(cur -> next[i]){
poi_Node p = cur -> fail;
while(p && !p -> next[i]) p = p -> fail;
cur -> next[i] -> fail = p ? p -> next[i] : root;
q.push(cur -> next[i]);
}
}
}
}
char str[2000000 + 5];
char bug[1005][55];
int cnt[1005];
void Search(char* s){
int len = strlen(s);
poi_Node cur = root;
for(int i = 0;i < len;++i){
int idx = s[i] - 'A';
if(idx < 0 || idx >= 26){
cur = root;
continue;
}
if(cur -> next[idx] == NULL){
while(cur && cur -> next[idx] == NULL) cur = cur -> fail;
if(cur == NULL) cur = root;
else cur = cur -> next[idx];
}else cur = cur -> next[idx];
poi_Node p = cur;
while(p){
if(p -> v > 0){
cnt[p -> v] ++;
}
p = p -> fail;
}
}
}
void DFS(poi_Node ROOT){
for(int i = 0; i < sigma_size;++i) if(ROOT -> next[i]) DFS(ROOT -> next[i]);
ROOT -> v = 0;
}
int main(){
// freopen("read.txt","r",stdin);
int n;
root = make_node();
while( sf("%d",&n) != EOF ){
memset(cnt,0,sizeof(cnt));
for(int i = 0;i < n;++i){
sf("%s",str);
strcpy(bug[i + 1],str);
Insert(str,i + 1);
}
get_fail();
sf("%s",str);
Search(str);
for(int i = 1;i <= n;++i){
if(cnt[i]){
pf("%s: %d\n",bug[i],cnt[i]);
}
}
DFS(root);
}
return 0;
}