标签:aac insert 世界 name color ras other ack 问题
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 28843 Accepted Submission(s): 6662
感觉AC自动机是个很神奇的数据结构,就像把字典树和KMP算法结合到了一起一样
#include<algorithm> #include<iostream> #include<cstring> #include<cstdio> #include<vector> #include<queue> using namespace std; const int N = 210 * 500; const int maxn = 128; struct Aho_Corasick{ int next[N][maxn], fail[N], data[N]; int root, sz; int newnode(){ for(int i = 0; i < maxn; i++) next[sz][i] = -1; data[sz] = -1; return sz++; } void Init() {sz = 0; root = newnode(); } void Insert(char *str, int v){ int len = strlen(str), u = root; for(int i = 0; i < len; i++){ if(next[u][str[i]] == -1) next[u][str[i]] = newnode(); u = next[u][str[i]]; } data[u] = v; } void Build(){ queue<int> Q; fail[root] = root; for(int i = 0; i < maxn; i++){ if(next[root][i] == -1) next[root][i] = root; else{ fail[next[root][i]] = root; Q.push(next[root][i]); } } while(!Q.empty()){ int u = Q.front(); Q.pop(); for(int i = 0; i < 128; i++){ if(next[u][i] == -1) next[u][i] = next[fail[u]][i]; else{ fail[next[u][i]] = next[fail[u]][i]; Q.push(next[u][i]); } } } } vector<int> res; bool Query(char *str, int v){ int len = strlen(str), u = root; res.clear(); for(int i = 0; i < len; i++){ u = next[u][str[i]]; int tmp = u; while(tmp != root){ if(data[tmp] != -1){ res.push_back(data[tmp]); } tmp = fail[tmp]; } } if(!res.size()) return false; sort(res.begin(), res.end()); printf("web %d:", v); for(int i = 0; i < res.size(); i++) printf(" %d", res[i]); printf("\n"); return true; } }AC; char str[10010]; int main(){ int n,m; scanf("%d",&n); AC.Init(); for(int i=1;i<=n;i++){ scanf("%s",str); AC.Insert(str,i); } AC.Build(); int ans=0; scanf("%d",&m); for(int i=1;i<=m;i++){ scanf("%s",str); if(AC.Query(str,i)) ans++; } printf("total: %d\n",ans); return 0; }
标签:aac insert 世界 name color ras other ack 问题
原文地址:http://www.cnblogs.com/Pretty9/p/7413103.html