Pagini recente » Cod sursa (job #1755074) | Cod sursa (job #72176) | Cod sursa (job #2887006) | Cod sursa (job #1515151) | Cod sursa (job #1446308)
# 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)
{
matches[matchesCount++] = i - patternLength;
q = Prefix[q];
}
}
}
int main()
{
const char *inFileName = "strmatch.in";
FILE *inFile = fopen(inFileName, "r");
fscanf(inFile, "%s %s", Pattern + 1, Text + 1);
fclose(inFile);
textLength = strlen(Text + 1);
patternLength = strlen(Pattern + 1);
Compute_Prefix_Function();
KMP_Match();
const char *outFileName = "strmatch.out";
FILE *outFile = fopen(outFileName, "w");
fprintf(outFile, "%d\n", matchesCount);
matchesCount = matchesCount < max_matches ? matchesCount : max_matches;
for (int i = 0; i < matchesCount; ++i)
fprintf(outFile, "%d ", matches[i]);
fprintf(outFile, "\n");
fclose(outFile);
return 0;
}