Nu aveti permisiuni pentru a descarca fisierul grader_eval.c

Cod sursa(job #1526809)

Utilizator sunt_emoSunt emo sunt_emo Data 17 noiembrie 2015 12:57:35
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <fstream>
#include <vector>

bool equal(const char *a, const char *b, int size)
{
	int it = 0;
	while (it < size && *a == *b)
		it++, a++, b++;
	return it == size;
}

int main()
{
	std::ifstream in("strmatch.in");
	std::string data, key;
	in >> key >> data;
	std::vector<int> results;
	
	if (key.size() <= data.size())
	{
		long long base = 15121, m = 15485863;
		long long key_hash = 0, rolling_hash = 0;
		long long p = 1;
		for (unsigned i = 0; i < key.size(); i++)
		{
			key_hash = (key_hash * base + key[i]) % m;
			rolling_hash = (rolling_hash * base + data[i]) % m;
			p = (p * base) % m;
		}
		
		for (unsigned i = key.size(); i < data.size(); i++)
		{
			if (key_hash == rolling_hash)// && equal(&data[i - key.size()], &key[0], key.size()))
				results.push_back(i - key.size());
			rolling_hash = (rolling_hash * base + data[i]) % m;
			rolling_hash -= (p * data[i - key.size()]) % m;
			if (rolling_hash < 0)
				rolling_hash += m;
		}
		if (key_hash == rolling_hash)// && equal(&data[data.size() - key.size()], &key[0], key.size()))
			results.push_back(data.size() - key.size());
	}

	std::ofstream out("strmatch.out");
	out << results.size() << '\n';
	int s = std::min(1000, static_cast<int>(results.size()));
	for (int i = 0; i < s; i++)
		out << results[i] << ' ';
	out << '\n';
}