POJ-3461.cpp 937 B

123456789101112131415161718192021222324252627282930
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. using namespace std;
  5. int main() {
  6. ios::sync_with_stdio(false);
  7. cin.tie(nullptr);
  8. int tests; cin >> tests;
  9. while (tests--) {
  10. string pattern, text; cin >> pattern >> text;
  11. vector<int> pi(pattern.size());
  12. for (int i = 1; i < static_cast<int>(pattern.size()); ++i) {
  13. int j = pi[i - 1];
  14. while (j > 0 && pattern[i] != pattern[j]) j = pi[j - 1];
  15. if (pattern[i] == pattern[j]) ++j;
  16. pi[i] = j;
  17. }
  18. int matched = 0, answer = 0;
  19. for (char c : text) {
  20. while (matched > 0 && c != pattern[matched]) matched = pi[matched - 1];
  21. if (c == pattern[matched]) ++matched;
  22. if (matched == static_cast<int>(pattern.size())) {
  23. ++answer;
  24. matched = pi[matched - 1];
  25. }
  26. }
  27. cout << answer << '\n';
  28. }
  29. }