Cod sursa(job #2784681)

Utilizator GrizzyProblemSolver79cNot telling GrizzyProblemSolver79c Data 17 octombrie 2021 00:11:22
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("strmatch.in");
ofstream fout("strmatch.out");

int const NMAX = 2000000;
string x, y;
int pre[1 + NMAX + 1 + NMAX];

void buildPre(string x) {
  //we already know pre[0] = 0, so we go directly to pre[1]
  int i = 0, j = 1;
  while(j < x.size()) {
    if(x[i] == x[j]) {
      i++;
      pre[j] = i;
      j++;
    } else {
      if(i == 0) {
        pre[j] = 0;
        j++;
      } else {
        i = pre[i-1];
      }
    }
  }
}

int main() {
  fin >> x >> y;
  buildPre(x + '$' + y);
  vector<int> sol;
  int ans = 0;

  for(int i = x.size(); i <= x.size() + y.size(); i++) {
    if(pre[i] == x.size()) {
      if(sol.size() < 1000) {
        sol.push_back(i - 2 * x.size());
      }
      ans++;
    }
  }

  /*int i = 0, j = 0;
  //i and j are the last matching letters in common prefix => x[0..i] matches y[j-L+1..j]

  while(j < y.size()) {
    if(x[i] == y[j]) {
      i++;
      j++;
    }
    if(i == x.size()) {
      if(sol.size() < 1000) {
        sol.push_back(j - x.size());
      }
      ans++;
      i = pre[i-1];
    } else if(i < x.size() && x[i] != y[j]) {
      if(i == 0) {
        j++;
      } else {
        i = pre[i-1];
      }
    }
  }*/
  fout << ans << "\n";
  for(auto i : sol) {
    fout << i << " ";
  }
  return 0;
}