najim

Untitled

Nov 16th, 2014
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<queue>
  4. #include<ctype.h>
  5. #include<ctype.h>
  6. #include<vector>
  7. #include<iostream>
  8. using namespace std;
  9. #define maxn 511*511
  10. #define maxc 26
  11. #define lowestChar 'a'
  12.  
  13. int ch[maxn][maxc];
  14. int val[maxn];
  15. int f[maxn];
  16. int cnt;
  17. int ans[maxn];
  18.  
  19. char str[1000010];
  20. char tmp[510];
  21.  
  22. /* ...... */
  23. vector<int>track[maxn];
  24. //vector<int>go[maxn];
  25. /* ...... */
  26.  
  27. void init()
  28. {
  29. cnt = 1;
  30. memset(ch[0],0,sizeof(ch[0]));
  31. memset(ans,0,sizeof(ans));
  32. memset(val,0,sizeof(val));
  33. memset(f,0,sizeof(f));
  34. for(int i=0;i<maxn;i++)
  35. {
  36. track[i].clear();
  37. //go[i].clear();
  38. }
  39. }
  40. void ac_insert_trie(char *s,int key)
  41. {
  42. int u = 0;
  43. while(*s)
  44. {
  45. int id = *s - lowestChar;
  46. if(ch[u][id] == 0)
  47. {
  48. memset(ch[cnt],0,sizeof(ch[cnt]));
  49. val[cnt] = 0;
  50. ch[u][id] = cnt++;
  51. }
  52. u = ch[u][id];
  53. s++;
  54. }
  55. val[u] = key;
  56. /* ...... */
  57. track[u].push_back(key);
  58. /* ...... */
  59. }
  60. void ac_get_fail()
  61. {
  62. queue<int> q;
  63. for(int c = 0; c < maxc; c++)
  64. {
  65. int u = ch[0][c];
  66. if(u)
  67. {
  68. f[u] = 0;
  69. q.push(u);
  70. }
  71. }
  72. while(!q.empty())
  73. {
  74. int r = q.front();
  75. q.pop();
  76. for(int c = 0; c < maxc; c++)
  77. {
  78. int u = ch[r][c];
  79. if(u)
  80. {
  81. q.push(u);
  82. int v = f[r];
  83. while(v && !ch[v][c]) v = f[v];
  84. f[u] = ch[v][c];
  85. }
  86. }
  87. }
  88. }
  89. void ac_find(int len)
  90. {
  91. int j = 0;
  92. for(int i = 0; i < len; i++)
  93. {
  94. int c = str[i] - lowestChar;
  95. while(j && !ch[j][c]) j = f[j];
  96. j = ch[j][c];
  97. int t = j;
  98. while(t && val[t])
  99. {
  100. /* ...... */
  101. for(int x=0;x<track[t].size();x++)
  102. {
  103. ans[track[t][x]]++;
  104. //go[track[t][x]].push_back(i);
  105. }
  106. /* ...... */
  107. t = f[t];
  108. }
  109. }
  110. }
  111.  
  112. int main()
  113. {
  114. int n;
  115. int kase,ks=0;
  116. scanf("%d",&kase);
  117. while(kase--)
  118. {
  119. scanf("%d",&n);
  120. init();
  121. scanf("%s",str);
  122. for(int i = 1; i <= n; i++)
  123. {
  124. scanf("%s",tmp);
  125. ac_insert_trie(tmp,i);
  126. }
  127. ac_get_fail();
  128. ac_find(strlen(str));
  129. printf("Case %d:\n",++ks);
  130. for(int i = 1; i <= n; i++)
  131. {
  132. printf("%d\n",ans[i]);
  133. }
  134. }
  135. return 0;
  136. }
Advertisement
Add Comment
Please, Sign In to add comment