Source code for submission s971

bugs.cpp

  1. #include <cstdio>
  2. #include <cstring>
  3. #include <algorithm>
  4. #include <string>
  5. #include <iostream>
  6.  
  7. using namespace std;
  8.  
  9. static int pi[1100];
  10.  
  11. /*void popn(string &s, int n) {
  12.   for(int i = 0; i < n; i++)
  13.   s.pop();
  14. }*/
  15.  
  16. void compute_prefix(string &P) {
  17. int m = P.length();
  18. pi[1] = 0;
  19. int k = 0;
  20.  
  21. for(int q=2; q <= m; q++) {
  22. while(k > 0 && P[k] != P[q-1]) {
  23. k = pi[k];
  24. }
  25. if(P[k] == P[q-1]) {
  26. k = k+1;
  27. }
  28. pi[q] = k;
  29. }
  30. }
  31.  
  32. void kmp_matcher(string &T, string &P) {
  33. int n = T.length();
  34. int m = P.length();
  35.  
  36. int q = 0;
  37. for (int i = 1; i <= n; i++) {
  38. while(q > 0 && P[q] != T[i-1]) {
  39. q = pi[q];
  40. }
  41. if(P[q] == T[i-1]) {
  42. q++;
  43. }
  44. if(q ==m ) {
  45. //cerr << i << " " << m << endl;
  46. T.erase(i-m, m);
  47. //cerr << T << endl;
  48. n = n-m;
  49. i -= 2*m-1;
  50. if (i < 1) i = 0;
  51. q = pi[q];
  52. }
  53. }
  54. }
  55.  
  56. int main()
  57. {
  58. string pat;
  59. uint cases;
  60. string text;
  61. while (cin >> cases >> pat >> ws)
  62. {
  63. for (uint c = 0; c < cases; ++c)
  64. {
  65. getline(cin, text);
  66. kmp_matcher(text, pat);
  67.  
  68. printf("%s\n", text.c_str());
  69. }
  70. }
  71. }