Pagini recente » Cod sursa (job #998115) | Cod sursa (job #304309) | Cod sursa (job #990484) | Cod sursa (job #1056647) | Cod sursa (job #415848)
Cod sursa(job #415848)
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
string a, b;
vector <int> rez;
long p1 = 3, win1 = 10000, p2 = 5, win2 = 9000, alen, blen, b_hash1, a_hash1, rez_size, def_power1, power1, power2, def_power2, a_hash2, b_hash2;
int main ()
{
//freopen ("strmatch.in", "rt", stdin);
//freopen ("strmatch.out", "wt", stdout);
ifstream f("strmatch.in");
ofstream g("strmatch.out");
cin.sync_with_stdio(false);
f>>a;
f>>b;
a_hash1 = 0;
b_hash1 = 0;
alen = a.size();
blen = b.size();
power1 = 1;
for (long i = alen - 1; i >= 0; --i)
{
a_hash1 += a[i] * power1;
b_hash1 += b[i] * power1;
def_power1 = power1;
power1 *= p1;
a_hash1 %= win1;
b_hash1 %= win1;
power1 %= win1;
}
a_hash2 = 0;
b_hash2 = 0;
power2 = 1;
for (long i = alen - 1; i >= 0; --i)
{
a_hash2 += a[i] * power2;
b_hash2 += b[i] * power2;
def_power2 = power2;
power2 *= p2;
a_hash2 %= win2;
b_hash2 %= win2;
power2 %= win2;
}
for (long i = alen; i < blen; ++i)
{
if (a_hash1 == b_hash1 && a_hash2 == b_hash2)
{
rez.push_back(i);
}
b_hash1 += (win1 - (def_power1 * b[i - alen] % win1));
b_hash1 %= win1;
if (b_hash1 < 0)
b_hash1 += win1;
b_hash1 *= p1;
b_hash1 += b[i];
b_hash1 %= win1;
b_hash2 += (win2 - (def_power2 * b[i - alen] % win2));
b_hash2 %= win2;
if (b_hash2 < 0)
b_hash2 += win2;
b_hash2 *= p2;
b_hash2 += b[i];
b_hash2 %= win2;
}
// printf("%ld\n", rez.size());
g<<rez.size()<<endl;
rez_size = rez.size();
for (long i = 0; i < rez_size && i < 1000; ++i)
// printf("%ld ", rez[i] - alen);
g<<rez[i] - alen<<" ";
g<<endl;
return 0;
}