AC Automatic Machine

Source: Internet
Author: User

A given n pattern string appears in the main string in a few

#include <cstdio>#include<cstring>Const intmaxpt=500007;//Maximum number of nodesConst intSize= -;//number of child nodesConst Charstart='a';//child node label correspondence relationship classac_automat{Private:    structNode {node*fail; Node*Next[size]; intCnt//various uses: counting, marking, etc.        BOOLFlag//does the word end        voidNewNode ()//Build Node{fail=NULL;  for(intI=0; i<size;i++) Next[i]=NULL; CNT=0; Flag=false;        }    }; Node*q[maxpt],h[maxpt],*Root; intfr,tl,t; Public:    voidInit () {FR= TL =0; T=0;        H[t].newnode (); Root= &h[t++]; }    voidInsert (Char*s) {intLen =strlen (s); Node*p =Root;  for(intI=0; i<len;i++)        {            intK = S[i]-start; if(P->next[k] = =NULL)                {H[t].newnode (); P->next[k] = &h[t++]; } P= p->Next[k]; } P->cnt++; P->flag=true; }    voidBuild () {root->fail =NULL; Q[TL]=Root;  while(Fr <=TL) {Node*tmp = q[fr++]; Node*p =NULL;  for(intI=0; i<size;i++)if(tmp->Next[i]) {                if(TMP = =root) tmp->next[i]->fail =Root; Else{p= tmp->fail;  while(P! =NULL) {                        if(p->Next[i]) {tmp->next[i]->fail = p->Next[i];  Break; } P= p->fail; }                    if(p = =NULL) TMP->next[i]->fail =Root; } q[++TL] = tmp->Next[i]; }        }    }        intQuery (Char*s) {intres =0; Node*p =Root; intLen =strlen (s);  for(intI=0; i<len;i++)        {            intK = S[i]-start;  while(P->next[k] = = NULL && P! =root) P= p->fail; P= p->Next[k]; if(p = = NULL) p =Root; Node*tmp =p;  while(tmp! = root && tmp->cnt! =-1)//modified with different query requirements{res+ = Tmp->CNT; TMP->cnt =-1; TMP= tmp->fail; }        }        returnRes; }}ac;Charstr[1000005],s[ -];intMain () {intT,i,n; scanf ("%d",&T);  while(t--) {scanf ("%d",&N); Ac.        Init ();  for(i=1; i<=n;i++) scanf ("%s", s), AC.        Insert (s); scanf ("%s", str); Ac.        Build (); printf ("%d\n", AC.    Query (str)); }    return 0;}

AC Automatic Machine

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.