Pagini recente » Cod sursa (job #2138640) | Cod sursa (job #1528751) | Cod sursa (job #1687764) | Cod sursa (job #1761636) | Cod sursa (job #1520208)
#include <fstream>
#include <string.h>
#define MOD1 100007
#define MOD2 100021
#define BAZA 73
#define N_MAX 2000002
#define MAX_PRINT 1000
using namespace std;
ifstream f("strmatch.in");
ofstream g("strmatch.out");
char a[N_MAX];
char b[N_MAX];
int aHash1, aHash2;
int bHash1, bHash2;
int pow1, pow2;
int sol[N_MAX];
int k;
int main()
{
int len1, len2;
int i;
f >> a;
f.get();
f >> b;
len1 = strlen(a);
len2 = strlen(b);
if (len1 > len2){
g << 0 << '\n';
return 0;
}
pow1 = pow2 = 1;
aHash1 = aHash2 = 0;
k = 0;
for (i = 0; i < len1; ++i){
aHash1 = (aHash1 * BAZA + a[i])%MOD1;
aHash2 = (aHash2 * BAZA + a[i])%MOD2;
if (i != 0){
pow1 = (pow1 * BAZA)%MOD1;
pow2 = (pow2 * BAZA)%MOD2;
}
}
bHash1 = bHash2 = 0;
for (i = 0; i < len1; ++i){
bHash1 = (bHash1 * BAZA + b[i])%MOD1;
bHash2 = (bHash2 * BAZA + b[i])%MOD2;
}
if (aHash1 == bHash1 && aHash2 == bHash2){
sol[k++] = 0;
}
for (i = len1; i < len2; ++i){
bHash1 = ((bHash1 - (b[i - len1] * pow1)%MOD1 + MOD1) * BAZA + b[i])%MOD1;
bHash2 = ((bHash2 - (b[i - len1] * pow2)%MOD2 + MOD2) * BAZA + b[i])%MOD2;
if (aHash1 == bHash1 && aHash2 == bHash2){
sol[k++] = i - len1 + 1;
}
}
g << k << '\n';
for (i = 0; i < k && i < MAX_PRINT; ++i){
g << sol[i] << ' ';
}
g << '\n';
f.close();
g.close();
return 0;
}
//#include <stdio.h>
//#include <string.h>
//
//#define MAXN 2000001
//
//#define P 73
//#define MOD1 100007
//#define MOD2 100021
//
//char A[MAXN], B[MAXN];
//int NA, NB;
//
//int hashA1, hashA2, P1, P2;
//
//char match[MAXN];
//
//int main()
//{
// freopen("strmatch.in", "rt", stdin);
// freopen("strmatch.out", "wt", stdout);
//
// scanf("%s %s", A, B);
// NA = strlen(A);
// NB = strlen(B);
//
// P1 = P2 = 1;
// hashA1 = hashA2 = 0;
// for (int i = 0; i < NA; i++)
// {
// hashA1 = (hashA1 * P + A[i]) % MOD1;
// hashA2 = (hashA2 * P + A[i]) % MOD2;
//
// if (i != 0)
// P1 = (P1 * P) % MOD1,
// P2 = (P2 * P) % MOD2;
// }
//
// if (NA > NB)
// {
// printf("0\n");
// return 0;
// }
//
// int hash1 = 0, hash2 = 0;
// for (int i = 0; i < NA; i++)
// hash1 = (hash1 * P + B[i]) % MOD1,
// hash2 = (hash2 * P + B[i]) % MOD2;
//
// int Nr = 0;
// if (hash1 == hashA1 && hash2 == hashA2)
// match[0] = 1, Nr++;
//
// for (int i = NA; i < NB; i++)
// {
// hash1 = ((hash1 - (B[i - NA] * P1) % MOD1 + MOD1) * P + B[i]) % MOD1;
// hash2 = ((hash2 - (B[i - NA] * P2) % MOD2 + MOD2) * P + B[i]) % MOD2;
//
// if (hash1 == hashA1 && hash2 == hashA2)
// match[ i - NA + 1 ] = 1, Nr++;
// }
// printf("%d\n", Nr);
//
// Nr = 0;
// for (int i = 0; i < NB && Nr < 1000; i++)
// if (match[i])
// Nr++,
// printf("%d ", i);
// printf("\n");
//
// return 0;
//}