Cod sursa(job #1699099)

Utilizator mihai995mihai995 mihai995 Data 6 mai 2016 05:01:19
Problema Potrivirea sirurilor Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;

const unsigned long long mod = 12060912947796127LL;
const int N = 1 + 2e6;

char text[N], pattern[N];

unsigned long long hist_adjust = 1, base = 31;
void set_hist_adjust(int n){
	while (n--) hist_adjust *= base;
}

unsigned long long push_chr(unsigned long long val, char A, char B = 'A' - 1){
	return val * base + (A - 'A' + 1) - (B - 'A' + 1) * hist_adjust;
}

void rabin_karp(char* text, char* pattern){
	unsigned long long need = 0, val = 0;
	vector<int> sol;

	int n = strlen(pattern);
	for (int i = 0; pattern[i]; i++){
		need = push_chr(need, pattern[i]);
		val  = push_chr(val, text[i]);
	}
	if (need == val) sol.push_back(0);
	set_hist_adjust(n);

	for (int i = n; text[i]; i++){
		val = push_chr(val, text[i], text[i - n]);
		if ( need == val ) sol.push_back(i - n + 1);
	}

	cout << sol.size() << '\n';
	if ( sol.size() > 1000 )
		sol.resize(1000);
	for (int x : sol)
		cout << x << ' ';
	cout << '\n';
}

int main(){
	freopen("strmatch.in", "r", stdin);
	freopen("strmatch.out", "w", stdout);

	cin >> pattern >> text;
	rabin_karp(text, pattern);

	return 0;
}