Pagini recente » Cod sursa (job #830204) | Cod sursa (job #2696394) | Cod sursa (job #2606359) | Cod sursa (job #1449902) | Cod sursa (job #997311)
Cod sursa(job #997311)
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <ctime>
using namespace std;
const int base = 97;
const int MOD1 = 131071;
const int MOD2 = 124287;
const int Nmax = 2000005;
char Pattern[Nmax], Text[Nmax];
int match[Nmax];
int HashPattern, HashText;
int HashPattern1, HashText1;
int base1 = 1, base2 = 1;
int P, T, contor;
void read()
{
ifstream f("strmatch.in");
f.getline( Pattern, Nmax );
f.getline( Text, Nmax );
P = strlen( Pattern );
T = strlen( Text );
f.close();
}
void calc_hash()
{
for ( int i = 0; i < P; ++i )
{
HashPattern = ( HashPattern * base + Pattern[i] ) % MOD1;
HashPattern1 = ( HashPattern1 * base + Pattern[i] ) % MOD2;
if ( i > 0 )
{
base1 = ( base1 * base ) % MOD1;
base2 = ( base2 * base ) % MOD2;
}
}
for ( int i = 0; i < P; ++i )
{
HashText = ( HashText * base + Text[i] ) % MOD1;
HashText1 = ( HashText1 * base + Text[i] ) % MOD2;
}
}
void Rabin_Karp()
{
if ( HashPattern == HashText && HashPattern1 == HashText1 )
match[1] = 1;
for ( int i = P; i < T; ++i )
{
HashText = ( ( HashText - ( Text[i - P] * base1 ) % MOD1 + MOD1 ) * base + Text[i] ) % MOD1;
HashText1 = ( ( HashText1 - ( Text[i - P] * base2 ) % MOD2 + MOD2 ) * base + Text[i] ) % MOD2;
if ( HashPattern == HashText && HashPattern1 == HashText1 )
match[i - P + 1] = 1;
}
}
void print()
{
ofstream g("strcmatch.out");
for ( int i = 1; i < T; ++i )
contor += match[i];
g << contor << "\n";
contor = 0;
for ( int i = 1; i < T; ++i )
{
if ( match[i] )
{
g << i << " ";
contor++;
if ( contor == 1000 )
break;
}
}
g.close();
}
int main()
{
read();
calc_hash();
Rabin_Karp();
print();
return 0;
}