自写的板子, 新鲜出炉, 所以不保证没 BUG, 慎用
- #include<iostream>
- using namespace std;
- #include<cstdio>
- #include<cstring>
- #include<queue>
- const int maxn = 26;
- struct Node{
- int mark;
- Node *next[maxn];
- Node *fail;
- Node(){
- mark = 0;
- for(int i=0;i<maxn;i++)
- next[i] = NULL;
- }
- ~Node(){
- for(int i=0;i<maxn;i++)
- if(next[i]!=NULL)
- delete next[i];
- }
- };
- struct Ac_Machine{
- Node *head;
- char hash(char s){// 压缩
- return s - a;
- }
- Ac_Machine(){
- head = NULL;
- }
- void init(){
- if(head!=NULL)
- delete head;
- head = new Node();
- }
- void insert(char *s,int len){
- Node *pt = head;
- for(int i=0;i<len;i++){
- int k = hash(s[i]);
- if(pt->next[k]==NULL){
- pt->next[k] = new Node();
- pt->next[k]->fail = head;
- }
- pt = pt->next[k];
- }
- pt->mark+=1;
- }
- void creat_fail(){
- queue<Node*> *team = new queue<Node*>();
- head->fail = NULL;
- for(int i=0;i<maxn;i++)
- if(head->next[i]!=NULL)
- team->push(head->next[i]);
- while(!team->empty()){
- Node *pt = team->front();
- team->pop();
- for(int i=0;i<maxn;i++){
- if(pt->next[i]==NULL)
- continue;
- team->push(pt->next[i]);
- Node *pd = pt->fail;
- while(pd!=NULL&&pd->next[i]==NULL)
- pd = pd->fail;
- if(pd!=NULL)
- pt->next[i]->fail = pd->next[i];
- }
- }
- delete team;
- }
- int Matching(char *s,int len){
- creat_fail();
- Node *pt = head;
- int ans = 0;
- for(int i=0;i<len;i++){
- int k = hash(s[i]);
- while(pt!=head&&pt->next[k]==NULL)
- pt = pt->fail;
- //cout<<s[i]<<""<<pt<<" "<<head<<" "<<pt->fail<<endl;;
- if(pt->next[k]!=NULL){
- // cout<<pt<<endl;
- pt = pt->next[k];
- Node *pd = pt;
- while(pd!=head&&pd->mark!=-1){
- // cout<<""<<pd<<"\tchar:"<<pd->mark<<" "<<pd->fail<<endl;
- ans += pd->mark;
- pd->mark = -1;
- pd = pd->fail;
- }
- }
- }
- return ans;
- }
- };
- Ac_Machine machine;
- char s[2000000];
- void deal(){
- int n;
- machine.init();
- scanf("%d",&n);
- for(int i=0;i<n;i++){
- scanf("%s",s);
- machine.insert(s,strlen(s));
- }
- scanf("%s",s);
- int ans = machine.Matching(s,strlen(s));
- printf("%d\n",ans);
- }
- int main(){
- int t;
- scanf("%d",&t);
- while(t--){
- deal();
- }
- return 0;
- }
来源: http://www.bubuko.com/infodetail-2537946.html