Pagini recente » Cod sursa (job #387683) | Cod sursa (job #1030311) | Cod sursa (job #975070) | Cod sursa (job #1545347) | Cod sursa (job #1485806)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 2000005
#define P 127
#define M 32749
int main() {
FILE* fin = fopen("strmatch.in", "r");
char* temp = (char *)malloc(MAX * sizeof(char));
fgets(temp, MAX, fin);
int sizeA = strlen(temp) - 1; //tratez stringul ca un array fara \0
char* A = (char*)malloc(sizeA * sizeof(char));
memcpy(A, temp, sizeA * sizeof(char));
fgets(temp, MAX, fin);
fclose(fin);
int sizeB = strlen(temp);
if(temp[sizeB - 1] == '\n') { //hz daca se termina cu \n sau nu
sizeB--;
}
char* B = (char*)malloc(sizeB * sizeof(char));
memcpy(B, temp, sizeB * sizeof(char));
free(temp);
FILE* fout = fopen("strmatch.out", "w");
if(sizeA > sizeB) {
fprintf(fout, "0\n");
free(A);
free(B);
fclose(fout);
return 0;
}
char* match = (char*)calloc(sizeB , sizeof(char));
int i;
int hashA = 0;
int hash = 0;
int invP = 1;
for(i=0; i<sizeA; i++) {
hashA = (hashA * P + A[i]) % M;
hash = (hash * P + B[i]) % M;
if(i != 0) {
invP = (invP * P) % M;
}
}
int nb = 0;
if(hash == hashA) {
nb++;
match[0] = 1;
}
for(i=sizeA; i<sizeB; i++) {
hash = ((hash - (B[i - sizeA] * invP) % M + M) * P + B[i]) % M;
if(hash == hashA) {
match[i - sizeA + 1] = 1;
nb++;
}
}
fprintf(fout, "%d\n", nb);
nb = 0;
for(i=0; i<sizeB && nb<1000; i++) {
if(match[i] == 1) {
fprintf(fout, "%d ", i);
nb++;
}
}
fprintf(fout, "\n");
free(match);
free(A);
free(B);
fclose(fout);
return 0;
}