Pagini recente » Rating Alin Ienei (arrow) | Cod sursa (job #2436150) | Cod sursa (job #602812) | Cod sursa (job #1671666) | Cod sursa (job #1360116)
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
#ifdef HOME
const string inputFile = "input.txt";
const string outputFile = "output.txt";
#else
const string problemName = "strmatch";
const string inputFile = problemName + ".in";
const string outputFile = problemName + ".out";
#endif
const int NMAX = 2000000 + 5;
const int BASE1 = 127;
const int BASE2 = 197;
const int MOD1 = (int)(1e6) + 3;
const int MOD2 = 666013;
int N, M;
int pi[NMAX];
char A[NMAX];
char B[NMAX];
int nr_matches;
int matches[1005];
int H1, H2;
int P1, P2;
void add(int i) {
nr_matches++;
if(nr_matches <= 1000)
matches[nr_matches] = i - N;
}
void hashes() {
int i;
P1 = P2 = 1;
H1 = H2 = 0;
for(i = 1; i <= N; i++) {
P1 = (P1 * BASE1) % MOD1;
P2 = (P2 * BASE2) % MOD2;
H1 = (H1 * BASE1 + A[i]) % MOD1;
H2 = (H2 * BASE2 + A[i]) % MOD2;
}
}
void rolling() {
int i, h1, h2;
h1 = h2 = 0;
for(i = 1; i < N; i++) {
h1 = (h1 * BASE1 + B[i]) % MOD1;
h2 = (h2 * BASE2 + B[i]) % MOD2;
}
for(i = N; i <= M; i++) {
h1 = (h1 * BASE1 + B[i]) % MOD1;
h1 = ((h1 - P1 * B[i - N]) % MOD1 + MOD1) % MOD1;
h2 = (h2 * BASE2 + B[i]) % MOD2;
h2 = ((h2 - P2 * B[i - N]) % MOD2 + MOD2) % MOD2;
if(h1 == H1 && h2 == H2)
add(i);
}
}
int main() {
int i;
freopen(inputFile.c_str(), "r", stdin);
freopen(outputFile.c_str(), "w", stdout);
scanf("%s", A + 1);
scanf("%s", B + 1);
N = strlen(A + 1);
M = strlen(B + 1);
hashes();
rolling();
printf("%d\n", nr_matches);
for(i = 1; i <= min(nr_matches, 1000); i++)
printf("%d ", matches[i]);
return 0;
}