Cod sursa(job #1526677)

Utilizator sunt_emoSunt emo sunt_emo Data 16 noiembrie 2015 23:52:39
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#include <vector>

std::vector<int> first_occurence(const std::string &data, const std::string &key)
{
	std::vector<int> v(key.size() + 1);
	v[0] = -1, v[1] = 0;
	std::vector<int> ret;

	for (unsigned i = 1; i < v.size() - 1; i++)
		v[i + 1] = key[i] == key[v[i]] ? v[i] + 1 : 0;

	unsigned it1 = 0, it2 = 0;
	while (it1 < data.size())
	{
		if (data[it1] == key[it2])
		{
			it1++, it2++;
			if (it2 == key.size())
			{
				ret.push_back(it1 - key.size());
				it2 = v[it2];
			}
			continue;
		}
		it2 = v[it2] < 0 ? it1++, 0 : v[it2];
	}

	return ret;
}

int main()
{
	std::ifstream in("strmatch.in");
	std::ofstream out("strmatch.out");
	std::string data, key;
	in >> key >> data;
	auto ret = first_occurence(data, key);
	out << ret.size() << '\n';
	int s = std::min(1000, static_cast<int>(ret.size()));
	for (int i = 0; i < s; i++)
		out << ret[i] << ' ';
	out << '\n';
}