Cod sursa(job #2284558)

Utilizator alex02Grigore Alexandru alex02 Data 17 noiembrie 2018 11:33:55
Problema Potrivirea sirurilor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

ifstream f("strmatch.in");
ofstream g("strmatch.out");

char tipar[2000001], sir[2000001], match[2000001];
int lungime_tipar, lungime_sir, hash_tipar1, hash_tipar2, P1, P2,p=73,mod1=100007, mod2=100021;

void citire()
{
    f.getline(tipar,2000001);
    cout<<tipar<<endl;
    f.get();
    f.getline(sir,2000001);
    cout<<sir<<endl;
}

void initializare()
{
	lungime_tipar = strlen(tipar);
	lungime_sir = strlen(sir);
    P1 = P2 = 1;
	hash_tipar1 = hash_tipar2 = 0;
}

void rezolvare()
{
    if (lungime_tipar > lungime_sir)
	{
		cout<<"0"<<endl;
		return;
	}


	for (int i = 0; i < lungime_tipar; i++)
	{
		hash_tipar1 = (hash_tipar1 * p + tipar[i]) % mod1;
		hash_tipar2 = (hash_tipar2 * p + tipar[i]) % mod2;

		if (i != 0)
        {
			P1 = (P1 * p) % mod1;
			P2 = (P2 * p) % mod2;
        }
	}

	int hash1 = 0, hash2 = 0;
	for (int i = 0; i < lungime_tipar; i++)
    {
		hash1 = (hash1 * p + sir[i]) % mod1;
		hash2 = (hash2 * p + sir[i]) % mod2;
    }


	int nr = 0;
	if (hash1 == hash_tipar1 && hash2 == hash_tipar2)
		match[0] = 1, nr++;

	for (int i = lungime_tipar; i < lungime_sir; i++)
	{
		hash1 = ((hash1 - (sir[i - lungime_tipar] * P1) % mod1 + mod1) * p + sir[i]) % mod1;
		hash2 = ((hash2 - (sir[i - lungime_tipar] * P2) % mod2 + mod2) * p + sir[i]) % mod2;

		if (hash1 == hash_tipar1 && hash2 == hash_tipar2)
			match[ i - lungime_tipar + 1 ] = 1, nr++;
	}
	cout<<nr<<endl;

	nr = 0;
	for (int i = 0; i < lungime_sir && nr < 1000; i++)
		if (match[i])
        {
			nr++;
			cout<<i+1<<" ";
        }
	cout<<endl;
}

int main()
{
    citire();
    initializare();
    rezolvare();
	return 0;
}