標籤:blog http io 資料 for 2014 ar 代碼
單詞統計的題目,給出一些單詞,統計有多少單詞在一個文本中出現,最經典的入門題了。
AC自動機的基礎:
1 Trie, 以這個資料結構為基礎的,不過增加一個fail指標和構造fail的函數
2 KMP,不是直接運用KMP,而是需要KMP的思想,KMP思想都沒有的話,理解這個演算法會更加吃力的。
注意本題的單詞會有重複出現的,一個單詞只能統計一次。
搜尋了一下網上的題解,發現好多代碼都是一大抄的啊,⊙﹏⊙b汗。
本部落格的乃是原創代碼,代碼風格也是差不多固定的,轉載請註明出處:http://blog.csdn.net/kenden23,不少所謂的IT網站轉載我的文章,不但連結沒給出,連作者也沒有,還好意思說自己是IT網站嗎?
請尊重作者,如果認為這些演算法代碼那麼好敲的,可以自己去敲去。
#include <cstdio>const int ARR_SIZE = 26;const int MAX_N = 10001;const int MAX_M = 1000001;const int MAX_KEY_LEN = 51;struct Node{Node *arr[ARR_SIZE];Node *fail;int n;};void clearNode(Node *rt){for (int i = 0; i < ARR_SIZE; i++){rt->arr[i] = NULL;}rt->n = 0;rt->fail = NULL;}Node *q[MAX_KEY_LEN*MAX_N], pool[MAX_KEY_LEN*MAX_N], *Trie;int head, tail, poolID;void insert(char *str){Node *pCrawl = Trie;for ( ; *str; str++){int id = *str - 'a';if (!pCrawl->arr[id]){pCrawl->arr[id] = &pool[poolID++];clearNode(pCrawl->arr[id]);}pCrawl = pCrawl->arr[id];}pCrawl->n++;}void buildFail(){Node *pCrawl;head = tail = 0;q[tail++] = Trie;while (head < tail){pCrawl = q[head++];for (int i = 0; i < ARR_SIZE; i++){if (pCrawl->arr[i] == NULL) continue;pCrawl->arr[i]->fail = Trie;//initialize all to TrieNode *fail = pCrawl->fail;while (fail){if (fail->arr[i])//find the first next up level match{//which make it the longest match and the best.pCrawl->arr[i]->fail = fail->arr[i];break;}fail = fail->fail;}//whi (p != NULL)q[tail++] = pCrawl->arr[i];}//for (int i = 0; i < kind; i++)}//while (head < tail)}int searchWordsInText(char *text){Node *pCrawl = Trie;int i = 0, ans = 0;while (text[i]){int id = text[i++] - 'a';//find the longest prefix matchwhile (!pCrawl->arr[id] && pCrawl != Trie) pCrawl = pCrawl->fail;if (pCrawl->arr[id]) pCrawl = pCrawl->arr[id];else continue;Node *tmp = pCrawl;while (tmp && tmp->n != -1){//If one word apprear multiply times, only count as one time.ans += tmp->n;tmp->n = -1;tmp = tmp->fail;}//traval through all words that end with text[i], add them to result}return ans;}int main(){int T, n;char keyWord[MAX_KEY_LEN], text[MAX_M];scanf("%d", &T);while (T--){Trie = &pool[0];clearNode(Trie);poolID = 1;scanf("%d", &n);getchar();while (n--){gets(keyWord);insert(keyWord);}gets(text);buildFail();printf("%d\n", searchWordsInText(text));}return 0;}