Cod sursa(job #799344)

Utilizator noctavianNastasie Ion Octavian noctavian Data 18 octombrie 2012 19:47:13
Problema Potrivirea sirurilor Scor 16
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>

using namespace std;

const unsigned long long hash_base = 7;

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

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

unsigned long long roll_hash(int oldv, unsigned long long hash, int newv, int exp) {
	hash -= hash_base*oldv;
	hash += hash_base*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();
	unsigned long long a_hash = init_hash(A);
	unsigned long long sub_hash = init_hash(B.substr(0, M));

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

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

    return 0;
}