标签:des style blog http color io os ar strong
Time Limit: 1000MS | Memory Limit: 32768KB | 64bit IO Format: %I64d & %I64u |
Description
Input
Output
Sample Input
Sample Output
1 #include <set> 2 #include <queue> 3 #include <vector> 4 #include <cstdio> 5 #include <cstdlib> 6 #include <cstring> 7 #include <iostream> 8 #include <algorithm> 9 using namespace std; 10 const int SONS = 26; 11 const int MAXN = 500100; 12 #define For(i,n) for(int i=1;i<=n;i++) 13 #define For0(i,n) for(int i=0;i<n;i++) 14 #define Rep(i,l,r) for(int i=l;i<=r;i++) 15 int T,ans,n; 16 char goal[MAXN*2]; 17 18 struct trie{ 19 int sz,ch[MAXN][SONS],v[MAXN],next[MAXN],Q[MAXN]; 20 void clr(){sz=0;memset(ch[0],0,sizeof(ch[0]));} 21 void insert(char *st){ 22 int len=strlen(st),cur=0; 23 For0(i,len){ 24 int id=st[i]-‘a‘; 25 if(!ch[cur][id]) { 26 ch[cur][id]=++sz; 27 v[sz]=0;memset(ch[sz],0,sizeof(ch[sz])); 28 } 29 cur=ch[cur][id]; 30 } 31 v[cur]++; 32 } 33 void BuildNext(){ 34 int l=0,r=0; 35 For0(i,SONS) 36 if(ch[0][i]) { 37 Q[++r]=ch[0][i]; 38 next[Q[r]]=0; 39 } 40 while(l<r){ 41 int cur=Q[++l]; 42 For0(i,SONS) 43 if(!ch[cur][i]) ch[cur][i]=ch[next[cur]][i]; 44 else{ 45 Q[++r]=ch[cur][i]; 46 next[ch[cur][i]]=ch[next[cur]][i]; 47 } 48 } 49 } 50 void match() { 51 int cur = 0,len=strlen(goal); 52 For0(i,len){ 53 int id = goal[i]-‘a‘;cur = ch[cur][id]; 54 int now = cur; 55 while(now) { 56 ans += v[now];v[now] = 0; 57 now = next[now]; 58 } 59 } 60 } 61 }ac; 62 63 int main(){ 64 scanf("%d",&T); 65 For(i,T){ 66 scanf("%d",&n); 67 ac.clr(); 68 while(n--){ 69 scanf("%s",&goal); 70 ac.insert(goal); 71 } 72 ac.BuildNext(); 73 scanf("%s",&goal); 74 ac.match(); 75 printf("%d\n",ans);ans=0; 76 } 77 return 0; 78 }
HDU2222(Keywords Search,AC自动机)
标签:des style blog http color io os ar strong
原文地址:http://www.cnblogs.com/kingnight/p/3977839.html