标签:des style io os ar for div sp 问题
Description
Input
Output
Sample Input
3 AA BB CC ooxxCC%dAAAoen....END
Sample Output
AA: 2 CC: 1 思路:AC自动机,加了个数组标记个数,新的模板#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; const int maxn = 1010; char str[maxn][maxn]; struct Trie { int next[1010*50][128], fail[1010*50], end[1010*50]; int root, L; int newNode() { for (int i = 0; i < 128; i++) next[L][i] = -1; end[L++] = -1; return L-1; } void init() { L = 0; root = newNode(); } void insert(char s[], int id) { int len = strlen(s); int now = root; for (int i = 0; i < len; i++) { if (next[now][s[i]] == -1) next[now][s[i]] = newNode(); now = next[now][s[i]]; } end[now] = id; } void build() { queue<int> Q; fail[root] = root; for (int i = 0; i < 128; 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 < 128; 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[1010]; void query(char buf[], int n) { for (int i = 0; i < n; i++) num[i] = 0; int len = strlen(buf); int now = root; for (int i = 0; i < len; i++) { now = next[now][buf[i]]; int temp = now; while (temp != root) { if (end[temp] != -1) num[end[temp]]++; temp = fail[temp]; } } for (int i = 0; i < n; i++) if (num[i]) printf("%s: %d\n", str[i], num[i]); } } ac; char buf[2000010]; int main() { int n; while (scanf("%d", &n) != EOF) { ac.init(); for (int i = 0; i < n; i++) { scanf("%s", str[i]); ac.insert(str[i], i); } ac.build(); scanf("%s", buf); ac.query(buf, n); } return 0; }
标签:des style io os ar for div sp 问题
原文地址:http://blog.csdn.net/u011345136/article/details/39525151