Cod sursa(job #1710632)

Utilizator M.AndreiMuntea Andrei Marius M.Andrei Data 29 mai 2016 14:45:54
Problema Potrivirea sirurilor Scor 14
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 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;

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

	for (size_t i = m; i < n; i++) {
		searchHash = ReHash(searchHash, text[i - m], text[i], pow);
		if (patternHash == searchHash) {
			bool ok = true;
			for (size_t j = i - m + 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));
		}
	}

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

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

	RabinKarp(pattern, text);

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