标签:
地址:http://acm.split.hdu.edu.cn/showproblem.php?pid=2896
题目:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 23013 Accepted Submission(s): 5551
1 #include <queue> 2 #include <cstring> 3 #include <cstdio> 4 using namespace std; 5 struct AC_auto 6 { 7 const static int LetterSize = 128; 8 const static int TrieSize = 128 * 510; 9 10 int tot,root,fail[TrieSize],end[TrieSize],next[TrieSize][LetterSize]; 11 12 int newnode(void) 13 { 14 memset(next[tot],-1,sizeof(next[tot])); 15 end[tot] = 0; 16 return tot++; 17 } 18 19 void init(void) 20 { 21 tot = 0; 22 root = newnode(); 23 } 24 25 int getidx(char x) 26 { 27 return (int)x; 28 } 29 30 void insert(char *ss,int x) 31 { 32 int len = strlen(ss); 33 int now = root; 34 for(int i = 0; i < len; i++) 35 { 36 int idx = getidx(ss[i]); 37 if(next[now][idx] == -1) 38 next[now][idx] = newnode(); 39 now = next[now][idx]; 40 } 41 end[now]=x; 42 } 43 44 void build(void) 45 { 46 queue<int>Q; 47 fail[root] = root; 48 for(int i = 0; i < LetterSize; i++) 49 if(next[root][i] == -1) 50 next[root][i] = root; 51 else 52 fail[next[root][i]] = root,Q.push(next[root][i]); 53 while(Q.size()) 54 { 55 int now = Q.front();Q.pop(); 56 for(int i = 0; i < LetterSize; i++) 57 if(next[now][i] == -1) next[now][i] = next[fail[now]][i]; 58 else 59 fail[next[now][i]] = next[fail[now]][i],Q.push(next[now][i]); 60 } 61 } 62 63 int match(char *ss,int n,int x) 64 { 65 int len,now,use[501],ff; 66 memset(use,0,sizeof use); 67 len = strlen(ss),now = root,ff=0; 68 for(int i = 0; i < len; i++) 69 { 70 int idx = getidx(ss[i]); 71 int tmp = now = next[now][idx]; 72 while(tmp) 73 { 74 if(end[tmp]) 75 use[end[tmp]]=1,ff=1; 76 tmp = fail[tmp]; 77 } 78 } 79 if(!ff)return 0; 80 printf("web %d:",x); 81 for(int j=1; j<=n; j++)if(use[j]) 82 printf(" %d",j); 83 printf("\n"); 84 return 1; 85 } 86 87 }; 88 89 AC_auto ac; 90 char ss[10011]; 91 int main(void) 92 { 93 int n,m,ans=0; 94 scanf("%d",&n); 95 ac.init(); 96 for(int i=1; i<=n; i++) 97 scanf("%s",ss),ac.insert(ss,i); 98 scanf("%d",&m); 99 ac.build(); 100 for(int i=1; i<=m; i++) 101 { 102 scanf("%s",ss); 103 if(ac.match(ss,n,i)) 104 ans++; 105 } 106 printf("total: %d\n",ans); 107 return 0; 108 }
标签:
原文地址:http://www.cnblogs.com/weeping/p/5937122.html