Cod sursa(job #2720247)

Utilizator zerolightningIon Bobescu zerolightning Data 10 martie 2021 18:01:27
Problema Potrivirea sirurilor Scor 14
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

#define P 60
#define MOD 100007 

int N, M;

int shiftHash(int hash, int lastLetter, int newLetter, int h)
{
	return (P * (hash - h * lastLetter) + newLetter) % MOD;
}

int cc(char c)
{
	return (int)(c - '@');
}

void solve(string& pattern, string& space, int& K, vector<int>& sols)
{
	int hash1 = 0, hash2 = 0;

	int h = 1;
	for (int i = 0; i < N - 1; i++)
	{
		h = (h * P) % MOD;
	}

	for (int i = 0; i < N; i++)
	{
		hash1 = (P * hash1 + cc(pattern[i])) % MOD;
		hash2 = (P * hash2 + cc(space[i])) % MOD;
	}

	if (hash1 == hash2)
	{
		K++;
		sols.push_back(0);
	}

	for (int i = N; i < M; i++)
	{
		hash2 = shiftHash(hash2, cc(space[i - N]), cc(space[i]), h);
		if (hash1 == hash2)
		{
			K++;
			sols.push_back(i - N + 1);
		}

	}


}

int main()
{
	ifstream f("strmatch.in");
	ofstream g("strmatch.out");
	// Program
	string pattern, space;
	f >> pattern >> space;
	N = pattern.size();
	M = space.size();
	if (N > M)
	{
		g << 0;
	}
	else
	{
		int K = 0;
		vector<int> sols;
		solve(pattern, space, K, sols);

		g << K << endl;
		int toShow = min(K, 1000);
		for (int i = 0; i < toShow; i++)
		{
			g << sols[i] << " ";
		}
	}



	// Exit
	f.close();
	g.close();
	return 0;
}