Cod sursa(job #1485806)

Utilizator mike93Indricean Mihai mike93 Data 13 septembrie 2015 01:21:41
Problema Potrivirea sirurilor Scor 38
Compilator c Status done
Runda Arhiva educationala Marime 1.53 kb
#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;
}