Pagini recente » Cod sursa (job #172144) | Cod sursa (job #1404924) | Cod sursa (job #287906) | Cod sursa (job #1476853) | Cod sursa (job #1446307)
# include <cstdio>
# include <cstring>
# include <stdexcept>
using namespace std;
# define max_size 2000005
# define max_matches 1000
char Text[max_size];
char Pattern[max_size];
int Prefix[max_size];
int matchesCount, matches[max_matches];
int textLength, patternLength;
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 )
matches[matchesCount++] = i - patternLength;
else
return;
q = Prefix[q];
}
}
}
int main()
{
const char *inFileName = "strmatch.in";
FILE *inFile = fopen(inFileName, "r");
try
{
if (fscanf(inFile, "%s %s", Pattern + 1, Text + 1) == -1)
{
throw "Error reading from file.";
}
fclose(inFile);
}
catch (char *e)
{
printf("%s\n", e);
exit(1);
}
textLength = strlen(Text + 1);
patternLength = strlen(Pattern + 1);
Compute_Prefix_Function();
KMP_Match();
const char *outFileName = "strmatch.out";
FILE *outFile = fopen(outFileName, "w");
try
{
if (fprintf(outFile, "%d\n", matchesCount) == -1)
throw "Error writing in file.";
for (int i = 0; i < matchesCount; ++i)
{
if (fprintf(outFile, "%d ", matches[i]) == -1)
throw "Error writing in file.";
}
if (fprintf(outFile, "\n") == -1)
throw "Error writing in file.";
fclose(outFile);
}
catch (char *e)
{
printf("%s\n", e);
exit(2);
}
return 0;
}