fork(3) download
  1. /*
  2.   Copyright 2012 Jakub "Cubix651" Cisło
  3.   Searching pattern in text - KMP algorithm. Complexity: O(n+m)
  4. */
  5. #include <cstdio>
  6. #include <cstring>
  7. const int MAX = 10000005;
  8.  
  9. int t, n, m, p[MAX], x, w;
  10. char pat[MAX], txt[MAX];
  11.  
  12. int main()
  13. {
  14. scanf("%d", &t);
  15. while(t--)
  16. {
  17. scanf("%d", &n);
  18. scanf("%s", pat);
  19. scanf("%s", txt);
  20. m = strlen(txt);
  21.  
  22. //calculating prefix array of patern
  23. p[0] = -1;
  24. p[1] = x = w = 0;
  25. for(int i = 1; i < n; ++i)
  26. {
  27. x = p[i];
  28. while(x != -1 && pat[i] != pat[x])
  29. x = p[x];
  30. p[i+1] = x+1;
  31. }
  32.  
  33. //searching pattern in text with prefix array
  34. for(int i = 0; i < m; ++i)
  35. {
  36. x = w;
  37. while(x != -1 && txt[i] != pat[x])
  38. x = p[x];
  39. w = x+1;
  40. if(w == n)
  41. printf("%d\n", i-n+1);
  42. }
  43. }
  44. return 0;
  45. }
Success #stdin #stdout 0.01s 61320KB
stdin
3
2
na
banananobano
6
foobar
foo
9
foobarfoo
barfoobarfoobarfoobarfoobarfoo
stdout
2
4
3
9
15
21