Cod sursa(job #2706711)

Utilizator bubblegumixUdrea Robert bubblegumix Data 15 februarie 2021 17:45:42
Problema Potrivirea sirurilor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include<fstream>
#include<string.h>
#include<vector>
using namespace std;
const int LIM = 2000005;
char txt[LIM], pat[LIM];
int lps[LIM];
vector<int> sol;

ifstream f("strmatch.in");
ofstream g("strmatch.out");


void preproces_lps(char* pat, int M, int* lps)
{
	int len = 0;
	lps[0] = 0;
	int i = 1;
	while (i < M)
		if (pat[i] == pat[len])
			lps[i++] = ++len;	
		else
			if (len != 0)
				len = lps[len - 1];
			else
				lps[i++] = 0;
				
			
	
}
void pat_search(char* pat, char* txt)
{
	int m = strlen(pat);
	int n = strlen(txt);
	int i = 0, j = 0; 
	preproces_lps(pat, m, lps);
	 
	while (i < n)
	{
		if (pat[j] == txt[i])
		{
			i++;
			j++;
		}
		if (j == m)
		{
			sol.push_back(i - j);
			j = lps[j - 1];
		}
		else
			if (i < n && pat[j] != txt[i])
			{
				if (j != 0)
					j = lps[j - 1];
				else
					i++;
			}
	}

}

int main()
{ 
	ios_base::sync_with_stdio(false);
	f.tie(NULL);
	f.getline(pat, LIM);
	f.getline(txt, LIM);
	
	pat_search(pat, txt);


	g << sol.size() << endl;
	for (auto it : sol)
		g << it << " ";
}
/*
ABABDABACDABABCABAB
ABABCABAB
*/