Cod sursa(job #1224049)

Utilizator roxana.istratePoenaru Roxana roxana.istrate Data 29 august 2014 15:50:15
Problema Potrivirea sirurilor Scor 78
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <string>
#include <vector>

#define P 47

#define MOD1 %100007
#define MOD2 %100021

using namespace std;

int np, ns, P1, P2;
string patt, str;
int hash_pattern1, hash_pattern2;
int hash1, hash2;
vector<int> ans;

int main(){
	freopen("strmatch.in", "r", stdin);
	freopen("strmatch.out", "w", stdout);
	cin >> patt >> str;
	np = patt.size();
	ns = str.size();

	if (np > ns) 
		cout << "0";
	else{
		P1 = P2 = 1;
		for (int i = 0; i < np; i++){
			hash_pattern1 = (hash_pattern1 * P + patt[i]) MOD1;
			hash_pattern2 = (hash_pattern2 * P + patt[i]) MOD2;
			if (i != 0)
				P1 = (P1 * P) MOD1,
				P2 = (P2 * P) MOD2;
		}

		for (int j = 0; j < np; j++){
			hash1 = (hash1 * P + str[j]) MOD1;
			hash2 = (hash2 * P + str[j]) MOD2;
		}
		if (hash1 == hash_pattern1 && hash2 == hash_pattern2){
			ans.push_back(0);
		}

		for (int i = np; i < ns; i++)
		{
			hash1 = ((hash1 - (str[i - np] * P1) MOD1 + 100007) * P + str[i]) MOD1;
			hash2 = ((hash2 - (str[i - np] * P2) MOD2 + 100021) * P + str[i]) MOD2;
			if (hash1 == hash_pattern1 && hash2 == hash_pattern2){
				ans.push_back(i + 1);
			}
		}
		cout << ans.size() << "\n";
		for (int i = 0; i < ans.size() && i < 1000; i++){
			cout << ans[i] - np << " ";
		}
	}
	return 0;
}