Pagini recente » Cod sursa (job #1644657) | Cod sursa (job #2218104) | Cod sursa (job #2210368) | Cod sursa (job #3170504) | Cod sursa (job #1446227)
# 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)
{
if (matchesCount < max_matches - 1)
matches[matchesCount++] = i - patternLength;
else
return;
q = Prefix[q];
}
}
}
void printMatches()
{
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->printMatches();
return 0;
}