标签:style blog http java color os io for
3 aaa bbb ccc 2 aaabbbccc bbaacc
web 1: 1 2 3 total: 1
解题:AC自动机的模板题。。。。哎。。。改了一天。。。。终于满意了。。。。。。。。。。。。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <vector> 6 #include <climits> 7 #include <algorithm> 8 #include <cmath> 9 #include <queue> 10 #define LL long long 11 #define INF 0x3f3f3f 12 using namespace std; 13 const int maxn = 100000; 14 struct trie { 15 int cnt,id,wd[130],fail; 16 void init() { 17 id = cnt = 0; 18 fail = -1; 19 memset(wd,-1,sizeof(wd)); 20 } 21 } dic[maxn]; 22 int tot,ans[1100],total; 23 void insertWord(int root,int _id,char *s) { 24 for(int i = 0; s[i]; i++) { 25 int k = s[i] - 31; 26 if(dic[root].wd[k] == -1) { 27 dic[tot].init(); 28 dic[root].wd[k] = tot++; 29 } 30 root = dic[root].wd[k]; 31 } 32 dic[root].cnt++; 33 dic[root].id = _id; 34 } 35 void build(int root) { 36 queue<int>q; 37 q.push(root); 38 while(!q.empty()) { 39 int u = q.front(); 40 q.pop(); 41 for(int i = 0; i < 130; i++) { 42 if(dic[u].wd[i] == -1) continue; 43 if(!u) dic[dic[u].wd[i]].fail = 0;//如果是第二层的节点 44 else { 45 int v = dic[u].fail; 46 while(v && dic[v].wd[i] == -1) 47 v = dic[v].fail; 48 //回溯到离根较远并与当前字符相同的点 49 if(dic[v].wd[i] != -1) 50 dic[dic[u].wd[i]].fail = dic[v].wd[i]; 51 else dic[dic[u].wd[i]].fail = 0; 52 } 53 q.push(dic[u].wd[i]); 54 } 55 } 56 } 57 58 void query(int root,char *s) { 59 bool vis[510] = {false}; 60 for(int i = 0; s[i]; i++) { 61 int k = s[i] - 31; 62 while(root && dic[root].wd[k] == -1) 63 root = dic[root].fail;//不如当前字符匹配,回溯 64 root = dic[root].wd[k];//dic[root].wd[k]与当前字符匹配 65 if(root == -1) root = 0;//trie树上不存在与之匹配的 66 else { 67 int v = root; 68 while(v && !vis[dic[v].id]) { 69 //如果当前节点访问过了, 70 //从当前节点的回溯路径上的节点也被访问了 71 if(dic[v].cnt) { 72 vis[dic[v].id] = true; 73 ans[total++] = dic[v].id; 74 } 75 v = dic[v].fail; 76 } 77 } 78 } 79 } 80 int main() { 81 int n,m,i,j,t = 0; 82 char word[300],text[11000]; 83 scanf("%d",&n); 84 dic[0].init(); 85 tot = 1; 86 for(i = 1; i <= n; i++) { 87 scanf("%s",word); 88 insertWord(0,i,word); 89 } 90 build(0); 91 scanf("%d",&m); 92 for(i = 1; i <= m; i++) { 93 total = 0; 94 scanf("%s",text); 95 query(0,text); 96 if(total) { 97 t++; 98 sort(ans,ans+total); 99 printf("web %d:",i); 100 for(j = 0; j < total; j++) 101 printf(" %d",ans[j]); 102 printf("\n"); 103 } 104 } 105 printf("total: %d\n",t); 106 return 0; 107 }
标签:style blog http java color os io for
原文地址:http://www.cnblogs.com/crackpotisback/p/3873974.html