light oj 1427(ac自动机)
2016-07-31 15:52
295 查看
#include <bits/stdc++.h> using namespace std; const int N = 510*505; const int M = 27; map<string,int>Map; struct Trie { int next [M],fail ,end ; int root,L; int newnode() { for(int i = 0; i < 26; i++) next[L][i] = -1; end[L++] = -1; return L - 1; } void init() { L = 0; root = newnode(); } void insert(string s,int id) { int len = s.size(); int now = root; for(int i = 0; i < len; i++) { if(next[now][s[i]-'a'] == -1) next[now][s[i] - 'a'] = newnode(); now = next[now][s[i] - 'a']; } end[now] = id; } void build() { queue<int>Q; fail[root] = root; for(int i = 0; i < 26; 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 now = Q.front(); Q.pop(); for(int i = 0; i < 26; i++) { if(next[now][i] == -1) next[now][i] = next[fail[now]][i]; else { fail[next[now][i]] = next[fail[now]][i]; Q.push(next[now][i]); } } } } int num[1000]; void query(char buf[],int n,int mm[]) { for(int i = 1; i <= n; i++) num[i] = 0; int len = (int)strlen(buf); int now = root; for(int i = 0; i < len; i++) { now = next[now][buf[i]-'a']; int temp = now; while( temp != root ) { if( end[temp] != -1) num[end[temp]]++; temp = fail[temp]; } } for(int i = 1; i <= n; i++) printf("%d\n",num[mm[i]]); } }; char buf[1000100]; Trie ac; void solve() { ac.init(); int n, l = 0; scanf("%d",&n); scanf("%s",buf); Map.clear(); int twice[1005]; memset(twice,0,sizeof(twice)); for(int i = 1; i <= n; i++) { string ss; cin>>ss; int c = Map[ss]; if(c == 0) { Map[ss] = ++l; ac.insert(ss,l); } twice[i] = Map[ss]; //int tmp = Map[ss]; } ac.build(); ac.query(buf,n,twice); } int main(void) { int t,cnt = 0; scanf("%d",&t); while(t--) { printf("Case %d:\n",++cnt); solve(); } return 0; }
相关文章推荐
- lightoj 1427 Substring Frequency (II) (ac自动机)
- LightOJ 题目1427 - Substring Frequency (II)(AC自动机)
- LightOJ 1427 Substring Frequency (II)(ac自动机水题)
- LightOJ 1427 -Repository(ac自动机)
- LightOJ - 1427 - Substring Frequency (II)(AC自动机)
- LightOJ 1427 Substring Frequency (II) (AC自动机)
- lightoj 1427 Substring Frequency (||) (AC自动机)
- LA 4670 Dominating Patterns (AC自动机)
- hdu 3065 AC自动机
- ZOJ 3494 BCD Code (AC自动机+数位DP,5级)
- 字符串处理-AC自动机
- HDU 3341 Lost's revenge (AC自动机+DP,5级)
- hdu 3065 病毒侵袭持续中(AC自动机)
- bzoj 4327: JSOI2012 玄武密码 (AC自动机)
- hdu2896 病毒侵袭 (AC自动机)
- BZOJ 3172: [Tjoi2013]单词 AC自动机
- hdu 2222 Keywords Search(AC自动机入门题)
- hdu 2896 病毒侵袭 (AC自动机)
- HDU3065-AC自动机
- AC自动机通配符匹配