Pagini recente » Cod sursa (job #2175169) | Cod sursa (job #1267154) | Cod sursa (job #146262) | Cod sursa (job #2111509) | Cod sursa (job #2032911)
#include <fstream>
#include <string>
#include <vector>
using namespace std;
ifstream in("strmatch.in");
ofstream out("strmatch.out");
#define p 10000007
#define q 666013
#define B 73
bool Find(string T, int start, int end, string P)
{
for (int i = start; i <= end; i++)
{
if (T[i] != P[i - start])
{
return false;
}
}
return true;
}
vector<int> RabinKarp(string T, string P)
{
if (P.size() > T.size())
return vector<int>();
int p_hash = 0;
int p_hash2 = 0;
int t_hash = 0;
int t_hash2 = 0;
int B_m = 1;
int B_m2 = 1;
vector<int> occ;
for (int i = 0; i < P.size(); i++)
{
p_hash = (p_hash * B + P[i]) % p;
p_hash2 = (p_hash2 * B + P[i]) % q;
t_hash = (t_hash * B + T[i]) % p;
t_hash2 = (t_hash2 * B + T[i]) % q;
}
for (int i = 0; i < P.size() - 1; i++)
{
B_m = (B_m * B) % p;
B_m2 = (B_m2 * B) % q;
}
if (p_hash == t_hash && p_hash2 == t_hash2 )
{
//if (Find(T, 0, P.size() - 1, P))
occ.push_back(0);
}
for (int i = P.size(); i < T.size(); i++)
{
t_hash = ((((t_hash - (T[i - P.size()] * B_m)%p + p)%p ) * B)%p + T[i])%p;
t_hash2 = ((((t_hash2 - (T[i - P.size()] * B_m2) % q + q) % q) * B) % q + T[i]) % q;
if (t_hash == p_hash && p_hash2 == t_hash2)
{
//if (Find(T, i - P.size() + 1, i, P))
{
occ.push_back(i - P.size() + 1);
if (occ.size() == 1000)
break;
}
}
}
return occ;
}
int main()
{
string A, Bs;
in >> A >> Bs;
vector<int> occ = RabinKarp(Bs, A);
out << occ.size() << '\n';
for (int i = 0; i< occ.size(); i++)
{
out << occ[i] << ' ';
}
}