HDU 2896 AC自动机

来源:互联网 发布:李炎恢php 编辑:程序博客网 时间:2024/06/06 18:47

AC自动机模板

code:
#include <iostream>#include <cstring>#include <queue>#include <vector>#include <algorithm>using namespace std;const int N = 60010;int ans = 0;char w[205], s[10010];struct AC_Auto{int ch[N][128], f[N], val[N], sz;vector<int> word;/**存模式串下标*/AC_Auto(){memset(ch, 0, sizeof ch);memset(f, 0, sizeof f);memset(val, 0, sizeof val);sz = 1;}void insert(char *t, int id){int u = 0;for(int i = 0; t[i]; ++i){int c = (int)t[i];if(!ch[u][c]) ch[u][c] = sz++;u = ch[u][c];}val[u] = id;}void getFail(){queue<int>q;q.push(0);while(!q.empty()){int t = q.front();q.pop();for(int c = 0; c < 128; ++c){if(ch[t][c]){int u = ch[t][c], v = f[t];q.push(u);while(v && !ch[v][c]) v = f[v];f[u] = t ? ch[v][c] : 0;}}}}void query(char *t, int cas){int u = 0;for(int i = 0; t[i]; ++i){int c = (int)t[i];while(u && !ch[u][c]) u = f[u];u = ch[u][c];int tmp = u;while(tmp){/**while实现last数组*/                if(val[tmp]) word.push_back(val[tmp]);                tmp = f[tmp];}}if(word.size()) {                ++ans;                sort(word.begin(), word.end());                cout << "web " << cas << ":";                    for(int i = 0; i < word.size(); ++i) cout << " " << word[i];                cout << endl;                word.clear();            }}}ac;int main(){int n, m;cin >> n;for(int i = 1; i <= n; ++i){cin >> w;ac.insert(w, i);}ac.getFail();cin >> m;for(int cas = 1; cas <= m; ++cas){cin >> s;ac.query(s, cas);}cout << "total: " << ans << endl;return 0;}




0 0
原创粉丝点击