Pagini recente » Cod sursa (job #2936851) | Cod sursa (job #2806039) | Cod sursa (job #2377459) | Cod sursa (job #1090486) | Cod sursa (job #2860639)
#include <bits/stdc++.h>
using namespace std;
ifstream f("strmatch.in");
ofstream g("strmatch.out");
vector<int> rabin_karp(string const& s, string const& t) {
const int p = 31;
const int m = 1e9 + 9;
int S = s.size(), T = t.size();
vector<long long> p_pow(max(S, T));
p_pow[0] = 1;
for (int i = 1; i < (int)p_pow.size(); i++)
p_pow[i] = (p_pow[i - 1] * p) % m;
vector<long long> h(T + 1, 0);
for (int i = 0; i < T; i++)
h[i + 1] = (h[i] + (t[i] - 'a' + 1) * p_pow[i]) % m;
long long h_s = 0;
for (int i = 0; i < S; i++)
h_s = (h_s + (s[i] - 'a' + 1) * p_pow[i]) % m;
vector<int> occurences;
for (int i = 0; i + S - 1 < T; i++) {
long long cur_h = (h[i + S] + m - h[i]) % m;
if (cur_h == h_s * p_pow[i] % m)
occurences.push_back(i);
}
return occurences;
}
#define d 256
vector<int> search(string pat, string txt, int q = 71) {
int M = pat.size();
int N = txt.size();
int i, j;
int p = 0; // hash value for pattern
int t = 0; // hash value for txt
int h = 1;
vector<int> ans;
// The value of h would be "pow(d, M-1)%q"
for (i = 0; i < M - 1; i++)
h = (h * d) % q;
// Calculate the hash value of pattern and first
// window of text
for (i = 0; i < M; i++) {
p = (d * p + pat[i]) % q;
t = (d * t + txt[i]) % q;
}
// Slide the pattern over text one by one
for (i = 0; i <= N - M; i++) {
// Check the hash values of current window of text
// and pattern. If the hash values match then only
// check for characters one by one
if (p == t) {
bool flag = true;
/* Check for characters one by one */
for (j = 0; j < M; j++) {
if (txt[i + j] != pat[j]) {
flag = false;
break;
}
}
// if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1]
if (j == M)
ans.push_back(i);
}
// Calculate hash value for next window of text: Remove
// leading digit, add trailing digit
if (i < N - M) {
t = (d * (t - txt[i] * h) + txt[i + M]) % q;
// We might get negative value of t, converting it
// to positive
if (t < 0)
t = (t + q);
}
}
return ans;
}
#define NMax 2000005
int M, N;
char A[NMax], B[NMax];
int pi[NMax], pos[1024];
void make_prefix(void) {
int i, q = 0;
for (i = 2, pi[1] = 0; i <= M; ++i) {
while (q && A[q + 1] != A[i]) {
q = pi[q];
}
if (A[q + 1] == A[i]) {
++q;
}
pi[i] = q;
}
}
int main() {
string A, B;
f >> A >> B;
int i, q = 0, n = 0;
for (; (A[M] >= 'A' && A[M] <= 'Z') || (A[M] >= 'a' && A[M] <= 'z') || (A[M] >= '0' && A[M] <= '9'); ++M)
;
for (; (B[N] >= 'A' && B[N] <= 'Z') || (B[N] >= 'a' && B[N] <= 'z') || (B[N] >= '0' && B[N] <= '9'); ++N)
;
for (i = M; i; --i) A[i] = A[i - 1];
A[0] = ' ';
for (i = N; i; --i) B[i] = B[i - 1];
B[0] = ' ';
make_prefix();
for (i = 1; i <= N; i++) {
while (q && A[q + 1] != B[i]) {
q = pi[q];
}
if (A[q + 1] == B[i]) {
++q;
}
if (q == M) {
q = pi[M];
++n;
if (n <= 1000) {
pos[n] = i - M;
}
}
}
g << n << endl;
for (i = 1; i <= min(n, 1000); ++i)
g << pos[i] << " ";
}