Pagini recente » Cod sursa (job #3177926) | Cod sursa (job #1525759) | Cod sursa (job #3216827) | Cod sursa (job #268732) | Cod sursa (job #3159950)
#include <stdio.h>
#include <string.h>
#define MAX_N 2000000
#define BASE1 217
#define BASE2 262
char str[MAX_N + 1];
int strLength;
char pattern[MAX_N + 1];
int patternLength;
void eraseNewLine(char str[], int& length) {
if (str[length - 1] == '\n')
str[--length] = 0;
}
bool cmp(char str[], char pattern[]) {
int i;
i = 0;
while (str[i] && pattern[i] && str[i] == pattern[i])
++i;
return pattern[i] == 0;
}
int main() {
FILE *fin, *fout;
fin = fopen("strmatch.in", "r");
fout = fopen("strmatch.out", "w");
int i;
int pHash1, pHash2;
int hash1, hash2;
int power1, power2;
bool patternFound;
int matches[1000];
int noMatches, noTotalMatches;
fgets(pattern, sizeof(pattern), fin);
patternLength = strlen(pattern);
eraseNewLine(pattern, patternLength);
fgets(str, sizeof(str), fin);
strLength = strlen(str);
eraseNewLine(str, strLength);
pHash1 = pHash2 = 0;
hash1 = hash2 = 0;
power1 = power2 = 1;
for (i = 0; i < patternLength; ++i) {
pHash1 = pHash1 * BASE1 + pattern[i];
pHash2 = pHash2 * BASE2 + pattern[i];
hash1 = hash1 * BASE1 + str[i];
hash2 = hash2 * BASE2 + str[i];
if (i > 0) {
power1 = power1 * BASE1;
power2 = power2 * BASE2;
}
}
noMatches = noTotalMatches = 0;
i = patternLength;
while (i <= strLength) {
patternFound = hash1 == pHash1 && hash2 == pHash2;
hash1 -= str[i - patternLength] * power1;
hash2 -= str[i - patternLength] * power2;
hash1 = hash1 * BASE1 + str[i];
hash2 = hash2 * BASE2 + str[i];
if (patternFound) {
++noTotalMatches;
if (noMatches < 1000)
matches[noMatches++] = i - patternLength;
}
++i;
}
fprintf(fout, "%d\n", noTotalMatches);
for (i = 0; i < noMatches; ++i)
fprintf(fout, "%d ", matches[i]);
fclose(fin);
fclose(fout);
return 0;
}