Cod sursa(job #1240362)

Utilizator vlad2901Vlad Berindei vlad2901 Data 11 octombrie 2014 08:00:15
Problema Potrivirea sirurilor Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <string>
#include <fstream>
#include <vector> 
#include <iostream> 

using namespace std;

#define MOD 666013
#define BASE 79

ifstream fin("strmatch.in");
ofstream fout("strmatch.out");

int main() {
	string s, p;
	fin >> p >> s;
	int lp = p.size();
	int phash = 0, shash = 0, val = 1;
	for (int i = 0; i < lp - 1; ++i) {
		phash = (phash * BASE + (p[i] - '0')) % MOD;
		shash = (shash * BASE + (s[i] - '0')) % MOD;
		cout << phash << " " << shash << endl; 				
		val = (val * BASE) % MOD;
	}
	cout << val << endl;
	while (phash < 0) {
		phash += MOD;
	}

	while (shash < 0) {
		shash += MOD;
	}
	phash = (phash * BASE + p[lp - 1] - '0') % MOD;
	shash = (shash * BASE + s[lp - 1] - '0') % MOD;
	cout << phash << " " << shash << endl; 
	int total = 0;
	vector<int> positions;
	if (phash == shash) {
		int ok;
		for (int j = 0; j < lp; ++j) {
			ok = 1;
			if (p[j] != s[j]) {
				ok = 0;
				break;
			}
		}
		if (ok) {
			++total;
			positions.push_back(0);
		}
	}
	for (int i = 1; i < s.size() - lp + 1; ++i) {
		shash = ((shash - val * (s[i-1] - '0')) * BASE + s[i + lp - 1] - '0') % MOD;
		if (shash < 0) {
			shash += MOD;
		}
		cout << phash << " " << shash << endl; 
		if (phash == shash) {
			int ok = 1;
			for (int j = i; j < i + lp; ++j) {
				if (p[j - i] != s[j]) {
					ok = 0;
					break;
				}
			}
			if (ok) {
				++total;
				positions.push_back(i);
			}
		}
	}
	fout << total << endl;
	for (int i = 0; i < positions.size(); ++i) {
		fout << positions[i] << " ";
	}
	return 0;
}