Cod sursa(job #2404045)

Utilizator puzzleFlutur Vasile puzzle Data 12 aprilie 2019 11:31:53
Problema Potrivirea sirurilor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <iostream>
#include <fstream>
#include <string>
#include <queue>

std::ifstream in("strmatch.in");
std::ofstream out("strmatch.out");

void PreProcessPattern(std::string pattern, int* LPS);

int KMP_Search(std::string pattern, std::string text, std::queue<int>& Solutii)
{
	int Aparitii = 0;

	int M = pattern.size();
	int N = text.size();

	int LPS[100];

	PreProcessPattern(pattern, LPS);

	int i = 0; //index for text
	int j = 0; //index for pattern

	while (i < N)
	{
		if (pattern[j] == text[i])
		{
			i++;
			j++;
		}
		if(j == M)
		{
			Aparitii++;
			Solutii.push(i-j);
			j = LPS[j - 1];
		}
		else if(i < N && pattern[j] != text[i])
		{
			if (j != 0)
				j = LPS[j - 1];
			else
				i++;
		}
	}

	return Aparitii;
}

void PreProcessPattern(std::string pattern, int* LPS)
{
	//Length of the previous longest prefix suffix
	int len = 0;

	//LPS[0] is always 0
	LPS[0] = 0;

	//The loop calculates LPS[i]
	int i = 1;
	while (i < pattern.size())
	{
		if (pattern[i] == pattern[len])
		{
			len++;
			LPS[i] = len;
			i++;
		}
		else
		{
			if (len != 0)
			{
				len = LPS[len - 1];
			}
			else //len == 0
			{
				LPS[i] = 0;
				i++;
			}
		}
	}

}

int main()
{
	std::queue<int> Solutii;

	std::string pattern;
	in >> pattern;
	
	std::string text;
	in >> text;

	int Aparitii = KMP_Search(pattern, text, Solutii);
	//int LPS[100];
	//PreProcessPattern(pattern, LPS);
	//std::cout << Aparitii;
	
	std::cout << Aparitii;
	std::cout << '\n';

	while (Solutii.size())
	{
		std::cout << Solutii.front()<<" ";
		Solutii.pop();
	}
	std::cin.get();

}