标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 15893 Accepted Submission(s): 4055
3 aaa bbb ccc 2 aaabbbccc bbaacc
web 1: 1 2 3 total: 1
坑啊,可见字符32 - 126。。。
思路:用word[]数组记录病毒字符串的编号。
AC代码:
#include <cstdio> #include <cstring> #include <queue> #include <algorithm> #define MAXN 100000+10 using namespace std; char str[MAXN]; struct Trie { int next[MAXN][100], fail[MAXN], word[MAXN]; int root, L; int newnode() { for(int i = 0; i < 100; i++)//醉了 不只是小写字母 next[L][i] = -1; word[L++] = -1; return L-1; } void init() { L = 0; root = newnode(); } void Insert(char *buf, int id) { int len = strlen(buf); int now = root; for(int i = 0; i < len; i++) { if(next[now][buf[i]-' '] == -1) next[now][buf[i]-' '] = newnode(); now = next[now][buf[i]-' ']; } word[now] = id;//记录病毒id } //构造失配指针 void build() { queue<int> Q; fail[root] = root; for(int i = 0; i < 100; 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 < 100; 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]); } } } } bool mark[510];//mark[i]标记病毒i有没有出现在 该网站 int Query(char *buf, int n, int id) { int len = strlen(buf); int now = root; memset(mark, false, sizeof(mark)); bool flag = false;//标记在该网站有没有找到病毒 for(int i = 0; i < len; i++) { now = next[now][buf[i]-' ']; int temp = now; while(temp != root) { if(word[temp] != -1)//非初始化值 { mark[word[temp]] = true; flag = true;//找到病毒 } temp = fail[temp]; } } if(!flag)//没有找到病毒 return false; else { printf("web %d: ", id);//网站有病毒 int t = 0; for(int i = 1; i <= n; i++)//输出 { if(mark[i]) { if(t > 0) printf(" "); printf("%d", i); t++; } } printf("\n"); return true; } } }; Trie ac; int main() { int N, M; while(scanf("%d", &N) != EOF) { 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, N, i))//该网站有病毒 ans++; } printf("total: %d\n", ans); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/chenzhenyu123456/article/details/47777045