Cod sursa(job #2450538)

Utilizator r00t_Roman Remus r00t_ Data 23 august 2019 16:49:23
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <algorithm>
#include <vector>
#include <fstream>
#include <cmath>
#include <iomanip>
#include <queue>
#include <tuple>
#include <limits>
#include <stdio.h>
#include <string.h>
#include <string>
using namespace std;

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

#define ff first
#define ss second

int lps[2000100];

void calcLPS(string pat)
{
	int j = 0, i = 1;
	lps[0] = 0;
	while(i < pat.size())
	{
		if (pat[i] == pat[j])
		{
			lps[i] = j + 1;
			j++;
			i++;
		}
		else
		{
			while (pat[i] != pat[j] && j > 0) 
				j = lps[j - 1];
			if (pat[i] == pat[j])
				lps[i] = j + 1;
			else
				i++;
		}


	}
}

void kmpSearch(string &needle, string &haystack)
{
	vector<int>sol;
	int i = 0, j = 0;
	while (i < haystack.size())
	{
		if (needle[j] == haystack[i]) i++, j++;
		else
		{
			while (j > 0 && needle[j] != haystack[i])
				j = lps[j - 1];
			
			if (j == 0 && needle[j] != haystack[i]) i++;
		}

		if (j == needle.size()) {
			sol.push_back(i - needle.size());
		} 

	}
	int k = sol.size();
	fout << k << '\n';

	for (i = 0; i < min(k,1000); i++)
	{
		fout << sol[i] << ' ';
	}
}



int main()
{
	string needle, haystack;
	fin >> needle >> haystack;
	calcLPS(needle);
	kmpSearch(needle, haystack);

}