Cod sursa(job #1446221)

Utilizator Rares95Rares Arnautu Rares95 Data 1 iunie 2015 03:26:27
Problema Potrivirea sirurilor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
# include <cstdio>
# include <string>
# include <iostream>
# include <cstring>
using namespace std;

# define max_size 2000005
# define max_matches 1000

class KMP
{
private:
	char Text[max_size];
	char Pattern[max_size];
	int Prefix[max_size];
	int matchesCount, matches[max_matches];
	int textLength, patternLength;

public:
	KMP(char text[], char pattern[])
	{
		for (int i = 0; i < max_size; ++i)
		{
			Text[i] = text[i];
			Pattern[i] = pattern[i];
		}
		textLength = strlen(Text) - 1;
		patternLength = strlen(Pattern) - 1;
	}

	void Compute_Prefix_function()
	{
		Prefix[1] = 0;
		int k = 0;
		for (int q = 2; q <= patternLength; ++q)
		{
			while (k > 0 && Pattern[k + 1] != Pattern[q])
				k = Prefix[k];
			if (Pattern[k + 1] == Pattern[q])
				++k;
			Prefix[q] = k;
		}
	}

	void KMP_Match()
	{
		Compute_Prefix_function();
		int q = 0;
		matchesCount = 0;
		for (int i = 1; i <= textLength; ++i)
		{
			while (q > 0 && Pattern[q + 1] != Text[i])
				q = Prefix[q];
			if (Pattern[q + 1] == Text[i])
				++q;
			if (q == patternLength)
			{
				matches[matchesCount++] = i - patternLength;
				q = Prefix[q];
			}
		}
	}

	void printSolution()
	{
		try
		{
			FILE *fout = fopen("strmatch.out", "w");
			matchesCount = matchesCount < max_matches ? matchesCount : max_matches;
			if (fprintf(fout, "%d\n", matchesCount) == -1)
				throw "Error writing.";
			for (int i = 0; i < matchesCount; ++i)
				if (fprintf(fout, "%d ", matches[i]) == -1)
					throw "Error writing.";
			if (fprintf(fout, "\n") == -1)
				throw "Error writing.";
			fclose(fout);
		}
		catch (char *error)
		{
			printf("%s", error);
		}
	}

};

char text[max_size], pattern[max_size];

int main()
{
	text[0] = pattern[0] = 'a';
	
	try
	{
		FILE *fin = fopen("strmatch.in", "r");

		if (fscanf(fin, "%s", pattern + 1) == -1)
			throw "Error reading.";
		if (fscanf(fin, "%s", text + 1) == -1)
			throw "Error reading.";
		fclose(fin);
	}
	catch (char *error)
	{
		printf("%s", error);
	}		

	//KMP *rez = new KMP(text, pattern);
	//rez->KMP_Match();
	//rez->printSolution();

	return 0;
}