Cod sursa(job #1710634)

Utilizator M.AndreiMuntea Andrei Marius M.Andrei Data 29 mai 2016 14:49:38
Problema Potrivirea sirurilor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <string>
#include <vector>
using namespace std;

ifstream f{ "strmatch.in" };
ofstream q{ "strmatch.out" };

#define PRIME 101
#define MOD 22801763489

long long ReHash(const long long& oldHash, const char& oldChar, const char& newChar, const long long& pow ) {
	return ((((oldHash - oldChar) / PRIME) + (newChar * pow)) % MOD);
}

void RabinKarp(const string& pattern, const string& text) {
	int n = (int)text.size();
	int m = (int)pattern.size();

	long long patternHash = 0;
	long long searchHash = 0;
	long long pow = 1;
	int count = 0;
	vector <int> pozitii;
	

	for (size_t i = 0; i < m; i++) {
		patternHash = (patternHash + pow * pattern[i]) % MOD;
		searchHash = (searchHash + pow * text[i]) % MOD;
		pow = (pow * PRIME) % MOD;
	}
	pow /= PRIME;

	for (size_t i = 1; i <= n - m + 1; i++) {
		if (patternHash == searchHash) {
			bool ok = true;
			for (size_t j = i - 1, k = 0; k < m && ok == true; j++, k++) {
				if (pattern[k] != text[j]) ok = false;
			}
			if (ok) count++;
			if (ok && count <= 1000) pozitii.push_back((int)(i - m + 1));
		}
		if (i < n - m + 1 )searchHash = ReHash(searchHash, text[i - 1], text[i + m - 1], pow);
	}

	q << count << "\n";
	for (auto& poz : pozitii) q << poz << " ";
}

int main() {
	string pattern, text;
	f >> pattern >> text;

	RabinKarp(pattern, text);

	f.close();
	q.close();
}