Cod sursa(job #2739222)

Utilizator vali_27Bojici Valentin vali_27 Data 7 aprilie 2021 11:28:41
Problema Potrivirea sirurilor Scor 14
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>

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

typedef unsigned long long ULL;
const int prime = 13;

ULL hash(const std::string& s, int start, int end)
{
	ULL h = 0, p = 1;
	for (int i = end; i>=start;--i)
	{
		h += s[i] * p;
		p *= prime;
	}
	return h;
}
 

void find(const std::string& s, const std::string& pattern)
{
	int patSize = pattern.size();
	int sSize = s.size();
	int count = 0;
	int apar[1000];
	ULL pathash = hash(pattern, 0, patSize - 1);
	ULL shash = hash(s, 0, patSize  - 1);
	ULL p = std::pow(prime, patSize - 1);
	
	for (int i = 0; i <= sSize - patSize; ++i)
	{
		if (pathash == shash)
		{
			bool ok = true;
			for (int k = 0; ok && k < patSize; ++k)
				if (s[i + k] != pattern[k])ok = false;

			if (ok)
			{
				apar[count++] = i;
				if (count == 1000)
				{
					break;
				}
			}
		}
		if (i + patSize < sSize)
			shash = (shash - p * s[i]) * prime + s[i + patSize];
	}
	g << count << '\n';
	for (int i = 0; i < count; ++i)
		g << apar[i] << ' ';
}

int main()
{
	std::string s, p;
	
	f >> p >> s;
	
	find(s, p);
}