Cod sursa(job #1234825)

Utilizator andreioneaAndrei Onea andreionea Data 28 septembrie 2014 05:21:34
Problema Potrivirea sirurilor Scor 14
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <string>
#include <vector>
#include <cstring>

#define BASE 7907

int main()
{
	std::string s1;
	std::string s2;
	std::ifstream f("strmatch.in");
	std::ofstream g("strmatch.out");
	std::getline(f, s1);
	std::getline(f, s2);
	f.close();
	long long hash = 0;
	for (auto &i : s1) {
		hash = hash * BASE + i;
	}
	long long k = 0, l = -s1.length();
	long long diff = 1;
	for (long long i = 1; i < s1.length(); ++i)
		diff *= BASE;
	long long hash2 = 0;
	int found = 0;
	std::vector<long long> sol;
	for (auto i = s2.begin(); i != s2.end(); ++i) {
		if (k < s1.length() - 1) {
			hash2 = hash2  * BASE +  (*i);
			k++, l++;
			continue;
		}
		else if(k == (s1.length() - 1)){
			hash2 = hash2  * BASE + (*i);
		}
		else {
			hash2 -= diff * (*(i - s1.length()));
			hash2 = hash2 * BASE + (*i);
		}
		k++, l++;
		if (hash == hash2 && !strncmp(s1.c_str(), s2.c_str() + l, s1.length())) {
			++found;
			sol.push_back(l);
			if (found == 1000)
				break;
		}
	}
	g << found << "\n";
	for (auto &i : sol)
		g << i << " ";
	g.close();
}