Cod sursa(job #1710638)

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

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

#define PRIME 101
#define MOD 2000099

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

bool checkEqual(const string& str1, const int& starti, const int& endi, const string& str2, const int&startf, const int& endf) {
	if (endf - startf != endi - starti) return false;
	for (int i = starti, j = startf; i <= endi && j <= endf; i++, j++) {
		if (str1[i] != str2[j]) return false;
	}
	return true;
}

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

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

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

	for (int i = 1; i <= n - m + 1; i++) {
		if (patternHash == searchHash) {
			if (checkEqual(text, i - 1, i + m - 2, pattern, 0, m - 1) == true) {
				pozitii.push_back((int)(i - 1));
			}
		}
		if (i < n - m + 1 )searchHash = ReHash(searchHash, text[i - 1], text[i + m - 1], pow);
	}

	q << pozitii.size() << "\n";
	int mins = min((int)pozitii.size(), 1000);
	for (int i = 0; i < mins; i++) q << pozitii[i] << " ";
}

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

	RabinKarp(pattern, text);

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