HDU 2222 Keywords Search AC自動機,hdu2222

來源:互聯網
上載者:User

HDU 2222 Keywords Search AC自動機,hdu2222

題目大意:給出一些單詞,和一個句子,問有多少個單詞在句子中出現過。


思路:來簽到吧


CODE:

#include <queue>#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#define P(a) ((a) - 'a')#define MAX 60#define _MAX 1000010using namespace std;char s[_MAX];struct Trie{    Trie *son[26],*fail;    int cnt;        Trie() {        memset(son,NULL,sizeof(son));        fail = NULL;        cnt = 0;    }    void Insert(char *s) {        Trie *now = this;        while(*s != '\0') {            if(now->son[P(*s)] == NULL)                now->son[P(*s)] = new Trie();            now = now->son[P(*s)];            ++s;        }        ++now->cnt;    }}*root;struct AC_Automaton{        void Build(int cnt) {        static char s[MAX];        for(int i = 1; i <= cnt; ++i) {            scanf("%s",s);            root->Insert(s);        }        static queue<Trie *> q;        while(!q.empty()) q.pop();        for(int i = 0; i < 26; ++i)            if(root->son[i] != NULL)                root->son[i]->fail = root,q.push(root->son[i]);        while(!q.empty()) {            Trie *now = q.front(); q.pop();            for(int i = 0; i < 26; ++i)                if(now->son[i] != NULL) {                    Trie *temp = now->fail;                    while(temp != root && temp->son[i] == NULL)                        temp = temp->fail;                    if(temp->son[i] != NULL)    temp = temp->son[i];                    now->son[i]->fail = temp;                    q.push(now->son[i]);                }        }    }    int Ask(char *s) {        int re = 0;        Trie *now = root;        while(*s != '\0') {            while(now != root && now->son[P(*s)] == NULL)                now = now->fail;            if(now->son[P(*s)] != NULL)                now = now->son[P(*s)];            for(Trie *temp = now; temp != root; temp = temp->fail)                re += temp->cnt,temp->cnt = 0;            ++s;        }        return re;    }}solver;int cases,cnt;int main(){    for(cin >> cases; cases--;) {        root = new Trie();        scanf("%d",&cnt);        solver.Build(cnt);        scanf("%s",s);        printf("%d\n",solver.Ask(s));    }    return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.