Cod sursa(job #3312542)

Utilizator depevladVlad Dumitru-Popescu depevlad Data 29 septembrie 2025 01:31:05
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <bits/stdc++.h>

using namespace std;

vector<int> prefix_function(const string& s) {
  int n = s.size();
  vector<int> pi(n);
  for (int i = 1; i < n; i++) {
    int j = pi[i - 1];
    while (j > 0 && s[i] != s[j]) j = pi[j - 1];
    if (s[i] == s[j]) j++;
    pi[i] = j;
  }
  return pi;
}

vector<int> kmp_search(const string& text, const string& pattern) {
  int n = text.size(), m = pattern.size();
  vector<int> pi = prefix_function(pattern);
  vector<int> matches;

  for (int i = 0, j = 0; i < n; i++) {
    while (j > 0 && text[i] != pattern[j]) j = pi[j - 1];
    if (text[i] == pattern[j]) j++;
    if (j == m) {
      matches.push_back(i - m + 1);
      j = pi[j - 1];
    }
  }
  return matches;
}

int main() {
#ifndef LOCAL
  freopen("strmatch.in", "r", stdin);
  freopen("strmatch.out", "w", stdout);
#endif
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  string pat, txt;
  cin >> pat >> txt;

  auto matches = kmp_search(txt, pat);
  cout << matches.size() << "\n";
  for (int i = 0; i < (int)matches.size() && i < 1000; i++) {
    if (i) cout << " ";
    cout << matches[i];
  }
  cout << "\n";
}