Pagini recente » Cod sursa (job #2862861) | Cod sursa (job #80511) | Cod sursa (job #930273) | Cod sursa (job #1459198) | Cod sursa (job #2032755)
#include <fstream>
#include <string>
#include <vector>
using namespace std;
ifstream in("strmatch.in");
ofstream out("strmatch.out");
#define p 1000001
#define B 101
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)
{
int p_hash = 0;
int t_hash = 0;
int B_m = 1;
vector<int> occ;
for (int i = 0; i < P.size(); i++)
{
p_hash = (p_hash * B + P[i]) % p;
t_hash = (t_hash * B + T[i]) % p;
}
for (int i = 0; i < P.size() - 1; i++)
{
B_m = (B_m * B) % p;
}
if (p_hash == t_hash && 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) * B)%p + T[i])%p;
if (t_hash < 0)
t_hash += p;
if (t_hash == p_hash)
{
if (Find(T, i - P.size() + 1, i, P))
{
occ.push_back(i - P.size() + 1);
}
}
}
return occ;
}
int main()
{
string A, Bs;
in >> A >> Bs;
vector<int> occ = RabinKarp(Bs, A);
out << occ.size() << endl;
for (int i = 0; i< occ.size() && i < 1000; i++)
{
out << occ[i] << ' ';
}
}