Cod sursa(job #2931511)

Utilizator matthriscuMatt . matthriscu Data 31 octombrie 2022 11:45:27
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <bits/stdc++.h>
using namespace std;

vector<size_t> getPrefixArray(const string& s) {
	vector<size_t> prefix(s.size());

	prefix[0] = 0;

	for (size_t i = 1, j = 0; i < s.size(); ++i) {
		while (j && s[i] != s[j])
			j = prefix[j - 1];

		j += (s[i] == s[j]);
		prefix[i] = j;
	}

	return prefix;
}

vector<size_t> kmp(const string& haystack, const string& needle) {
	vector<size_t> prefix = getPrefixArray(needle), ans;
	
	for (size_t i = 0, j = 0; i < haystack.size(); ++i) {
		while (j && haystack[i] != needle[j])
			j = prefix[j - 1];

		j += (haystack[i] == needle[j]);
		
		if (j == needle.size()) {
			j = prefix[j - 1];
			ans.push_back(i + 1 - needle.size());
		}
	}

	return ans;
}

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

    string needle, haystack;
	fin >> needle >> haystack;
	
	const vector<size_t> ans = kmp(haystack, needle);

	fout << ans.size() << '\n';
	for (auto it = ans.begin(); it != ans.end() && it != ans.begin() + 1000; ++it)
		fout << *it << ' ';
	fout << '\n';
}