Cod sursa(job #1183175)

Utilizator MarianMMorosac George Marian MarianM Data 8 mai 2014 16:31:34
Problema Potrivirea sirurilor Scor 18
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include <fstream>
#include <string>
#include <vector>
#include <list>
using namespace std;

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

#define PRIME 100007
// #define PRIME2 100021 - even more efficiency
#define D 123

string P, T;
int HashP, HashT, h = 1;
vector<int> s;	int nos;

int main(){
	int i, lgP, shift; char x;

	fin >> P; lgP = P.size();
	for (i = 0; i < lgP; i++) 
		HashP = (D * HashP + P[i]) % PRIME;
	
	fin.get(x); 
	for (i = 0; i < lgP; i++){
		fin.get(x); T += x;
		HashT = (D * HashT + T[i]) % PRIME;
	}
	
	for (i = 1; i < lgP; i++) h = (h * D) % PRIME;

	shift = 0;
	while (!fin.eof()){
		if (HashP == HashT){
				for (i = 0; i < lgP; i++)	if (P[i] != T[i + shift])	break;
				if (i == lgP){
					nos++; 
					if (nos <= 1000)
						s.push_back(shift);
				}
			}

		fin.get(x); T += x;
		HashT = ((HashT - (T[shift] * h) % PRIME + PRIME)*D + x) % PRIME;
		shift++;
	}

	fout << nos << '\n';
	for (i = 0; i < s.size() && i < 1000; i++) fout << s[i] << '\n';

	return 0;
}