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