Cod sursa(job #1710654)

Utilizator M.AndreiMuntea Andrei Marius M.Andrei Data 29 mai 2016 16:05:30
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 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 100007



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

	if (n < m) {
		q << "0";
		return;
	}

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

	pow = 1;

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

	if (patternHash == searchHash) {
		pozitii.push_back(0);
	}
	
	for (int i = m; i < n; i++) {
		searchHash = (((searchHash - text[i - m] * pow) % MOD  + MOD)* PRIME +text[i]) % MOD;
		if (patternHash == searchHash) {
			pozitii.push_back(i-m+1);
		}
	}

	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();
}