Pagini recente » Cod sursa (job #674174) | Cod sursa (job #2728939) | Cod sursa (job #2732138) | Cod sursa (job #1931311) | Cod sursa (job #2032957)
#include <fstream>
#include <vector>
#include <cstring>
using namespace std;
ifstream in("strmatch.in");
ofstream out("strmatch.out");
const int MAX = 2e6 + 1;
const int p = 100007;
const int q = 100021;
const int B = 73;
vector<int> occ (1000, 0);
bool Find(char*T, int start, int end, char* P)
{
for (int i = start; i <= end; i++)
{
if (T[i] != P[i - start])
{
return false;
}
}
return true;
}
void RabinKarp(char* T, int N, char* P, int M)
{
if (M > N)
return;
int p_hash1 = 0;
int p_hash2 = 0;
int t_hash1 = 0;
int t_hash2 = 0;
int B_m1 = 1;
int B_m2 = 1;
int count = 0;
for (int i = 0; i < M; i++)
{
p_hash1 = (p_hash1 * B + P[i]) % p;
p_hash2 = (p_hash2 * B + P[i]) % q;
t_hash1 = (t_hash1 * B + T[i]) % p;
t_hash2 = (t_hash2 * B + T[i]) % q;
if (i != 0)
{
B_m1 = (B_m1 * B) % p;
B_m2 = (B_m2 * B) % q;
}
}
if (p_hash1 == t_hash1 && p_hash2 == t_hash2 )
{
if (Find(T, 0, M - 1, P))
occ[count++] = 0;
}
for (int i = M; i < N; i++)
{
t_hash1 = ((((t_hash1 - T[i - M] * B_m1) % p + p) ) * B + T[i]) % p;
t_hash2 = ((((t_hash2 - T[i - M] * B_m2) % q + q) ) * B + T[i]) % q;
if (t_hash1 == p_hash1 && p_hash2 == t_hash2)
{
if (Find(T, i - M + 1, i, P))
{
occ[count++] = i - M + 1;
if (count == 1000)
break;
}
}
}
out << count << '\n';
for (int i = 0; i < count; i++)
{
out << occ[i] << ' ';
}
}
int main()
{
char *A = new char[MAX];
char *Bs = new char[MAX];
in >> A >> Bs;
RabinKarp(Bs, strlen(Bs), A, strlen(A));
}