日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

hdu 2222 ac自动机

發(fā)布時間:2024/2/28 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 hdu 2222 ac自动机 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

對于ac自動機的具體內(nèi)容,請看如下博客:http://www.cppblog.com/mythit/archive/2009/04/21/80633.html 寫的挺好的。

要了解ac自動機就要先知道trie樹,還有了解一點KMP算法。

trie樹的話 就是一個字典樹,把單詞在樹上排好,KMP的話 主要懂他的失敗指針。

ac自動機是處理字符串匹配的,查詢匹配字符串是否在主串中出現(xiàn)和如出現(xiàn),則出現(xiàn)的位置。


看代碼注釋



#include<cstdio> #include<iostream> #include<cstring> using namespace std;const int kind=26; struct node{node *fail;node *next[kind]; //所有26個字母int count; // 1代表是單詞的結(jié)尾,0代表不是node(){fail=NULL; count=0; memset(next,NULL,sizeof(next));} }*q[500001]; char keyword[55]; //匹配串 char str[1000004]; //主串 int head,tail;void insert(node *root,char *str) //建立一個字典樹 {node *p=root;int i=0,index;while(str[i]){index=str[i]-'a';if(p->next[index]==NULL) p->next[index]=new node(); //如果尚未出現(xiàn)在字典序中就創(chuàng)造一個p=p->next[index];i++;}p->count++; //令單詞的最后一個標(biāo)志為1 }void build_ac_automation(node *root){ //匹配失敗指針int i;root->fail=NULL;q[head++]=root;while(head!=tail){node *temp=q[tail++];node *p=NULL;for(i=0;i<26;i++){if(temp->next[i]!=NULL){if(temp==root) temp->next[i]->fail=root;else{p=temp->fail;while(p!=NULL){ //不斷尋找父節(jié)點的失敗指針,直到父節(jié)點的失敗指針指向節(jié)點的兒子節(jié)點與自己相同if(p->next[i]!=NULL){temp->next[i]->fail=p->next[i];break;}p=p->fail;}if(p==NULL) temp->next[i]->fail=root;}q[head++]=temp->next[i];}}} }int query(node *root){ //統(tǒng)計匹配串出現(xiàn)的次數(shù)。int i=0,cnt=0,index,len=strlen(str);node *p=root;while(str[i]){index=str[i]-'a';while(p->next[index]==NULL&&p!=root) p=p->fail;p=p->next[index];p=(p==NULL)?root:p;node *temp=p;while(temp!=root&&temp->count!=-1){ //避免重復(fù)計算cnt+=temp->count; temp->count=-1;temp=temp->fail;}i++;}return cnt; } int main() {int t;scanf("%d",&t);while(t--){int n;head=tail=0;node *root=new node();scanf("%d",&n);getchar();while(n--){scanf("%s",keyword);insert(root,keyword);}build_ac_automation(root);scanf("%s",str);printf("%d\n",query(root));}return 0; }

總結(jié)

以上是生活随笔為你收集整理的hdu 2222 ac自动机的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。