Pagini recente » Cod sursa (job #2692858) | Cod sursa (job #2301629) | Cod sursa (job #2807326) | Cod sursa (job #750227) | Cod sursa (job #1485807)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 2000005
#define P 127
#define M1 32749
#define M2 32719
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 hashA1 = 0;
int hashA2 = 0;
int hash1 = 0;
int hash2 = 0;
int invP1 = 1;
int invP2 = 1;
for(i=0; i<sizeA; i++) {
hashA1 = (hashA1 * P + A[i]) % M1;
hashA2 = (hashA2 * P + A[i]) % M2;
hash1 = (hash1 * P + B[i]) % M1;
hash2 = (hash2 * P + B[i]) % M2;
if(i != 0) {
invP1 = (invP1 * P) % M1;
invP2 = (invP2 * P) % M2;
}
}
int nb = 0;
if((hash1 == hashA1) && (hash2 == hashA2)) {
nb++;
match[0] = 1;
}
for(i=sizeA; i<sizeB; i++) {
hash1 = ((hash1 - (B[i - sizeA] * invP1) % M1 + M1) * P + B[i]) % M1;
hash2 = ((hash2 - (B[i - sizeA] * invP2) % M2 + M2) * P + B[i]) % M2;
if((hash1 == hashA1) && (hash2 == hashA2)) {
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;
}