Cod sursa(job #796836)

Utilizator noctavianNastasie Ion Octavian noctavian Data 12 octombrie 2012 18:59:33
Problema Potrivirea sirurilor Scor 14
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>

using namespace std;

const int hash_base = 47;

int init_hash(string s) {
	int hash = 0;
	int base = 1;

	for(int i = s.length()-1; i >= 0; i--) {
		hash += base * (int)s[i];
		base *= hash_base;
	}
	return hash;
}

int roll_hash(int oldv, int hash, int newv, int exp) {
	hash -= oldv*pow(hash_base, exp-1);
	hash *= hash_base;
	hash += newv;
	return hash;
}

int main() {
	string A, B;
	ifstream in("strmatch.in");
	in >> A >> B;
	in.close();

	vector<int> poz;
	int nr_matches = 0;
	int N = B.length();
	int M = A.length();
	int a_hash = init_hash(A);
	int sub_hash = init_hash(B.substr(0, M));

	for(int i = 0; i < N - M; i++) {
		if(a_hash == sub_hash)
			if(B.compare(i, M, A) == 0) {
				nr_matches++;
				if(nr_matches <= 1000)
					poz.push_back(i);
			}
		sub_hash = roll_hash((int)B[i], sub_hash, (int)B[i+M], M);
	}

	ofstream out("strmatch.out");
	out << nr_matches << endl;
	for(int i = 0; i < poz.size(); i++) 
		out << poz[i] << " ";
	out.close();

    return 0;
}