Cod sursa(job #1524143)

Utilizator AndreiIstetulAndrei Andrei AndreiIstetul Data 13 noiembrie 2015 16:29:18
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include <fstream>
#include <vector>
#include <string>
//#include <algorithm>

std::fstream in, out;
std::string text, pattern;
std::vector<int> pos, next;
int n, m;

void leUrmator()
{
	int k = -1, x;
	next[0] = 0;
	for (x = 1; x < m; ++x)
	{
		while (k > 0 && pattern[k + 1] != pattern[x]) k = next[x];

		if (pattern[k + 1] == pattern[x]) ++k;
		next[x] = k;
	}
}

int main()
{
    in.open("strmatch.in", std::fstream::in);
    out.open("strmatch.out", std::fstream::out);
	int i, x = -1;

    in >> pattern >> text;

	n = text.size();
	m = pattern.size();

	next.resize(m);

	leUrmator();

	for (i = 0; i < n; ++i)
	{
		while (x > 0 && pattern[x + 1] != text[i]) x = next[x];
		
		if (pattern[x + 1] == text[i]) ++x;
		if (x == m - 1)
		{
			pos.push_back(i - m + 1);
			x = next[x];
		}
	}

	int vlen = pos.size();
	out << vlen << "\n";
//	std::sort(pos.begin(), pos.end());
	for (i = 0; i < vlen && i < 1000; ++i) out << pos[i] << ' ';

    return 0;
}