Cod sursa(job #2284563)

Utilizator Bigiu_AndreiBigiu Andrei Bigiu_Andrei Data 17 noiembrie 2018 11:37:25
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <stdio.h>
#include <string.h>

#define MAXN 2000001

#define P 73
#define MOD1 100007
#define MOD2 100021

char a[MAXN], b[MAXN];
int NA, NB;
int has1, has2, P1, P2;
char match[MAXN];
int main()
{
	freopen("strmatch.in", "rt", stdin);
	freopen("strmatch.out", "wt", stdout);

	scanf("%s %s", a, b);
	NA = strlen(a);
	NB = strlen(b);

	P1 = P2 = 1;
	has1 = has2 = 0;
	for (int i = 0; i < NA; i++)
	{
		has1 = (has1 * P + a[i]) % MOD1;
		has2 = (has2 * P + a[i]) % MOD2;

		if (i != 0)
			P1 = (P1 * P) % MOD1,
			P2 = (P2 * P) % MOD2;
	}

	if (NA > NB)
	{
		printf("0\n");
		return 0;
	}

	int hash1 = 0, hash2 = 0;
	for (int i = 0; i < NA; i++)
		hash1 = (hash1 * P + b[i]) % MOD1,
		hash2 = (hash2 * P + b[i]) % MOD2;

	int Nr = 0;
	if (hash1 == has1 && hash2 == has2)
		match[0] = 1, Nr++;

	for (int i = NA; i < NB; i++)
	{
		hash1 = ((hash1 - (b[i - NA] * P1) % MOD1 + MOD1) * P + b[i]) % MOD1;
		hash2 = ((hash2 - (b[i - NA] * P2) % MOD2 + MOD2) * P + b[i]) % MOD2;

		if (hash1 == has1 && hash2 == has2)
			match[ i - NA + 1 ] = 1, Nr++;
	}
	printf("%d\n", Nr);

	Nr = 0;
	for (int i = 0; i < NB && Nr < 1000; i++)
		if (match[i])
			Nr++,
			printf("%d ", i);
	printf("\n");

	return 0;
}