Cod sursa(job #2364172)

Utilizator alex.mercan2014Mercan Alexandru alex.mercan2014 Data 3 martie 2019 21:53:15
Problema Potrivirea sirurilor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <string>
#include <vector>
#include <fstream>

std::vector<int> matches;

void computePrefix(std::string const&P, std::vector<int>&prefixes)
{
	int m = P.length();
	prefixes.resize(m + 1);
	prefixes[1] = 0;
	int k = 0;
	for (int q = 2; q <= m; q++)
	{
		while (k > 0 && P[k] != P[q - 1])
			k = prefixes[k];
		if (P[k] == P[q - 1])
			k++;
		prefixes[q] = k;
	}
}

void KMP(std::string const&T, std::string const&P)
{
	int n = T.length();
	int m = P.length();
	std::vector<int> prefixes;
	//prefixes[q] is the length of the longest prefix of P that is a proper suffix of Pq.
	computePrefix(P, prefixes);
	int q = 0;
	//for (auto a : prefixes)
	//	std::cout << a << " ";
	for (int i = 1; i <= n; i++)
	{
		while (q > 0 && P[q] != T[i - 1])
			q = prefixes[q];
		if (P[q] == T[i - 1])
			q++;
		if (q == m)
		{
			matches.push_back(i - m);
			q = prefixes[q];
		}
	}
}

int main()
{
	std::string a, b;
	std::ifstream fin("strmatch.in");
	std::ofstream fout("strmatch.out");
	fin >> a >> b;	
	KMP(b, a);
	fout << matches.size()<<"\n";
	for (auto a : matches)
		fout << a << " ";
	//std::cin.get();
	return 0;
}